import { AlertCircle, ClipboardList, Plus, RotateCcw } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import api from '../services/api';
import { formatJalaliDate } from '../utils/date';
import PwaCreateTaskSheet from './PwaCreateTaskSheet';
import { usePwaNotification } from './PwaNotificationProvider';
import PwaProjectActivityList from './PwaProjectActivityList';
import PwaProjectMemberList from './PwaProjectMemberList';
import PwaProjectProgress from './PwaProjectProgress';
import PwaProjectStatusSheet from './PwaProjectStatusSheet';
import PwaProjectTaskPreview from './PwaProjectTaskPreview';
import { pwaProjectStatusLabels } from './pwaProjectMeta';
import { hasPermission } from './pwaTaskMeta';

export default function PwaProjectDetail() {
  const { id } = useParams();
  const navigate = useNavigate();
  const { user } = useAuth();
  const { notify } = usePwaNotification();
  const [project, setProject] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [createOpen, setCreateOpen] = useState(false);
  const [statusOpen, setStatusOpen] = useState(false);

  const permissions = useMemo(() => ({
    canCreateTask: hasPermission(user, 'tasks.create'),
    canEditProject: hasPermission(user, 'projects.edit'),
  }), [user]);

  const fetchProject = async () => {
    setLoading(true);
    setError('');
    try {
      const { data } = await api.get(`/pwa/projects/${id}`);
      setProject(data.data);
    } catch (err) {
      setError(err.response?.data?.message || 'خطا در دریافت اطلاعات پروژه‌ها. دوباره تلاش کنید.');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { fetchProject(); }, [id]);

  const changeStatus = async (status) => {
    try {
      const { data } = await api.patch(`/pwa/projects/${id}/status`, { status });
      setProject((current) => ({ ...current, ...data.data }));
      setStatusOpen(false);
      notify({ tone: 'success', title: 'پروژه', message: 'وضعیت پروژه تغییر کرد.' });
    } catch (err) {
      notify({ tone: 'error', title: 'پروژه', message: err.response?.data?.message || 'تغییر وضعیت پروژه انجام نشد.' });
    }
  };

  if (loading) return <div className="pwa-skeleton detail" />;

  if (error) {
    return (
      <section className="pwa-state-card error">
        <AlertCircle size={28} />
        <strong>{error}</strong>
        <button type="button" onClick={fetchProject}>تلاش دوباره</button>
      </section>
    );
  }

  const counts = project.task_counts || {};

  return (
    <div className="pwa-project-detail">
      <section className="pwa-detail-card">
        <span className="pwa-eyebrow">جزئیات پروژه</span>
        <h1>{project.title}</h1>
        <div className="pwa-task-meta">
          <span className="pwa-chip">{pwaProjectStatusLabels[project.status] || project.status || 'نامشخص'}</span>
          <span className="pwa-chip">تسک‌ها: {counts.total || 0}</span>
        </div>
        <PwaProjectProgress value={project.progress} />
        <p>{project.description || 'توضیح کوتاهی برای این پروژه ثبت نشده است.'}</p>
      </section>

      <section className="pwa-project-actions">
        <button type="button" onClick={() => navigate(`/pwa/tasks?project_id=${project.id}`)}><ClipboardList size={16} /> مشاهده تسک‌ها</button>
        {permissions.canCreateTask && <button type="button" onClick={() => setCreateOpen(true)}><Plus size={16} /> ایجاد تسک برای این پروژه</button>}
        {permissions.canEditProject && <button type="button" onClick={() => setStatusOpen(true)}><RotateCcw size={16} /> تغییر وضعیت</button>}
      </section>

      <section className="pwa-detail-grid">
        <Info label="وضعیت" value={pwaProjectStatusLabels[project.status] || 'نامشخص'} />
        <Info label="مهلت" value={formatJalaliDate(project.due_date, 'بدون موعد')} />
        <Info label="مدیر پروژه" value={project.manager?.name || 'نامشخص'} />
        <Info label="تعداد اعضا" value={project.members_count || project.members?.length || 0} />
        <Info label="تسک‌های امروز" value={project.today_tasks_count || 0} />
        <Info label="عقب‌افتاده" value={counts.overdue || 0} />
      </section>

      <section className="pwa-card-section">
        <div className="pwa-section-title">
          <h2>تسک‌های پروژه</h2>
          <span>{project.tasks?.length || 0} مورد</span>
        </div>
        <PwaProjectTaskPreview tasks={project.tasks || []} />
      </section>

      <section className="pwa-card-section">
        <div className="pwa-section-title">
          <h2>اعضای پروژه</h2>
          <span>{project.members?.length || 0} نفر</span>
        </div>
        <PwaProjectMemberList members={project.members || []} />
      </section>

      <section className="pwa-card-section">
        <div className="pwa-section-title">
          <h2>فعالیت‌های اخیر</h2>
          <span>{project.activities?.length || 0} مورد</span>
        </div>
        <PwaProjectActivityList activities={project.activities || []} />
      </section>

      <PwaCreateTaskSheet
        open={createOpen}
        onClose={() => setCreateOpen(false)}
        initialProjectId={project.id}
        lockProject
        successMessage="تسک جدید برای این پروژه ایجاد شد."
        onCreated={fetchProject}
      />
      <PwaProjectStatusSheet open={statusOpen} project={project} onClose={() => setStatusOpen(false)} onChange={changeStatus} />
    </div>
  );
}

function Info({ label, value }) {
  return (
    <div className="pwa-detail-info">
      <span>{label}</span>
      <strong>{value}</strong>
    </div>
  );
}
