import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { AppBaseUrl } from '../BaseUrl';
import { useParams } from 'react-router-dom';
import moment from 'moment-jalaali';
import { FiUser, FiCalendar, FiClock, FiCheckCircle, FiXCircle, FiAlertCircle } from 'react-icons/fi';

const UserWorkroom = () => {
  const [projects, setProjects] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const param = useParams();
  const id = param?.id;

  useEffect(() => {
    const fetchProjects = async () => {
      try {
        const response = await axios.get(`${AppBaseUrl}/offers`, {
          params: { status_filter: "دریافت", id },
        });

        const offersFromSender = response.data.offerbyidsender?.docs || [];
        const offersFromReceiver = response.data.offerbyid?.docs || [];

        const mergedOffers = [...offersFromSender, ...offersFromReceiver];
        const sortedOffers = mergedOffers.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));

        setProjects(sortedOffers);
      } catch (err) {
        setError('خطا در بارگذاری درخواست‌ها');
      } finally {
        setLoading(false);
      }
    };

    fetchProjects();
  }, [id]);

  const formatJalaliDate = (date) => {
    if (!date) return 'نامشخص';
    return moment(date).format('jYYYY/jMM/jDD - HH:mm');
  };

  const StatusTag = ({ status }) => {
    const config = {
      accepted: { text: 'تایید شده', color: 'bg-green-900/30 text-green-300 border border-green-800', icon: <FiCheckCircle /> },
      rejected: { text: 'رد شده', color: 'bg-red-900/30 text-red-300 border border-red-800', icon: <FiXCircle /> },
      pending: { text: 'در انتظار', color: 'bg-yellow-900/30 text-yellow-300 border border-yellow-800', icon: <FiAlertCircle /> },
    };

    const { text, color, icon } = config[status] || { text: status, color: 'bg-gray-800 text-gray-400 border border-gray-700', icon: null };

    return (
      <span className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-xs font-medium ${color}`}>
        {icon}
        {text}
      </span>
    );
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20 bg-slate-950">
        <div className="animate-spin rounded-full h-12 w-12 border-4 border-cyan-500 border-t-transparent"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-red-900/20 border border-red-800 text-red-300 px-6 py-4 rounded-xl text-center max-w-md mx-auto mt-10">
        <p className="font-medium">{error}</p>
      </div>
    );
  }

  if (projects.length === 0) {
    return (
      <div className="bg-slate-900 border border-slate-800 text-slate-400 px-6 py-12 rounded-xl text-center max-w-md mx-auto mt-10">
        <FiAlertCircle className="mx-auto text-5xl mb-3 text-slate-600" />
        <p className="text-lg font-medium">هیچ درخواستی یافت نشد.</p>
      </div>
    );
  }

  return (
    <div className="min-h-screen  text-slate-100 p-4 sm:p-6 lg:p-8">
      <div className="max-w-7xl mx-auto">
        <div className="mb-8">
          <h2 className="text-2xl font-bold text-slate-50 flex items-center gap-2">
            <FiUser className="text-cyan-400" />
            لیست درخواست‌ها
          </h2>
          <p className="text-slate-400 mt-1">مجموع: <span className="text-cyan-400">{projects.length}</span> درخواست</p>
        </div>

        {/* موبایل: کارت‌ها */}
        <div className="block md:hidden space-y-4">
          {projects.map((project) => (
            <div
              key={project._id}
              className="bg-slate-800/50 backdrop-blur-sm rounded-xl border border-slate-700 p-5 hover:border-cyan-700/50 transition-all duration-300 hover:shadow-xl hover:shadow-cyan-900/20"
            >
              <div className="space-y-4">
                <div className="flex justify-between items-start">
                  <div>
                    <p className="text-xs font-medium text-slate-400">درخواست‌کننده</p>
                    <p className="text-lg font-bold text-cyan-400">
                      {project.sender
                        ? `${project.sender.first_name} ${project.sender.last_name}`
                        : 'نامشخص'}
                    </p>
                    <p className="text-sm text-slate-500">@{project.sender?.user_name}</p>
                  </div>
                  <StatusTag status={project.status} />
                </div>

                <div>
                  <p className="text-xs font-medium text-slate-400">درخواست‌شونده</p>
                  <p className="text-lg font-bold text-purple-400">
                    {project.receiver
                      ? `${project.receiver.first_name} ${project.receiver.last_name}`
                      : 'نامشخص'}
                  </p>
                  <p className="text-sm text-slate-500">@{project.receiver?.user_name}</p>
                </div>

                <div className="flex items-center gap-2 text-xs text-slate-400">
                  <FiCalendar className="text-cyan-500" />
                  <span>{formatJalaliDate(project.createdAt)}</span>
                </div>
                {project.updatedAt && (
                  <div className="flex items-center gap-2 text-xs text-slate-500">
                    <FiClock className="text-purple-500" />
                    <span>آخرین تغییر: {formatJalaliDate(project.updatedAt)}</span>
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>

        {/* دسکتاپ: جدول */}
        <div className="hidden md:block overflow-hidden rounded-xl border border-slate-700 bg-slate-900/50 backdrop-blur-sm shadow-2xl">
          <table className="w-full">
            <thead className="bg-gradient-to-r from-cyan-900/20 to-purple-900/20 border-b border-slate-700">
              <tr>
                <th className="px-6 py-4 text-right text-xs font-semibold text-slate-300">درخواست‌کننده</th>
                <th className="px-6 py-4 text-right text-xs font-semibold text-slate-300">درخواست‌شونده</th>
                <th className="px-6 py-4 text-center text-xs font-semibold text-slate-300">وضعیت</th>
                <th className="px-6 py-4 text-right text-xs font-semibold text-slate-300">تاریخ ثبت</th>
                <th className="px-6 py-4 text-right text-xs font-semibold text-slate-300">آخرین تغییر</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-700">
              {projects.map((project) => (
                <tr
                  key={project._id}
                  className="hover:bg-slate-800/50 transition-all duration-200"
                >
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div>
                      <p className="font-bold text-slate-100">
                        {project.sender
                          ? `${project.sender.first_name} ${project.sender.last_name}`
                          : 'نامشخص'}
                      </p>
                      <p className="text-sm text-cyan-400">@{project.sender?.user_name}</p>
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div>
                      <p className="font-bold text-slate-100">
                        {project.receiver
                          ? `${project.receiver.first_name} ${project.receiver.last_name}`
                          : 'نامشخص'}
                      </p>
                      <p className="text-sm text-purple-400">@{project.receiver?.user_name}</p>
                    </div>
                  </td>
                  <td className="px-6 py-4 text-center">
                    <StatusTag status={project.status} />
                  </td>
                  <td className="px-6 py-4 text-sm text-slate-300">
                    {formatJalaliDate(project.createdAt)}
                  </td>
                  <td className="px-6 py-4 text-sm text-slate-400">
                    {project.updatedAt ? formatJalaliDate(project.updatedAt) : '—'}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};

export default UserWorkroom;