import { useState, useEffect, useRef } from 'react';
import { useParams } from 'react-router-dom';
import api from '../services/api';
import StatusBadge from '../components/StatusBadge';
import PriorityBadge from '../components/PriorityBadge';
import EmptyState from '../components/EmptyState';
import { TableSkeleton } from '../components/LoadingSkeleton';
import FormSelect from '../components/FormSelect';
import toast from 'react-hot-toast';
import { Archive, Search, CheckCircle, Users, Paperclip, Calendar, FileText, UserPlus, Trash2 } from 'lucide-react';
import { formatJalaliDate, formatJalaliDateTime, isPastDate } from '../utils/date';

export default function ProjectDetail() {
  const { id } = useParams();
  const [project, setProject] = useState(null);
  const [loading, setLoading] = useState(true);
  const [tab, setTab] = useState('overview');
  const [tasks, setTasks] = useState([]);
  const [backlogItems, setBacklogItems] = useState([]);
  const [members, setMembers] = useState([]);
  const [users, setUsers] = useState([]);
  const [selectedMemberId, setSelectedMemberId] = useState('');
  const [addingMember, setAddingMember] = useState(false);
  const [removingMemberId, setRemovingMemberId] = useState(null);
  const [files, setFiles] = useState([]);
  const [meetings, setMeetings] = useState([]);
  const [activities, setActivities] = useState([]);
  const [uploading, setUploading] = useState(false);
  const fileInputRef = useRef(null);

  useEffect(() => {
    setLoading(true);
    api.get(`/projects/${id}`).then(({ data }) => {
      setProject(data.data);
      setMembers(data.data.members || []);
    }).catch(() => toast.error('خطا در دریافت اطلاعات پروژه'))
    .finally(() => setLoading(false));
  }, [id]);

  useEffect(() => {
    if (tab === 'tasks') api.get(`/tasks?project_id=${id}`).then(({ data }) => setTasks(data.data || [])).catch(() => {});
    if (tab === 'backlog') api.get('/backlog-items', { params: { project_id: id, archive_state: 'all', per_page: 100 } }).then(({ data }) => setBacklogItems(data.data || [])).catch(() => toast.error('خطا در دریافت بک‌لاگ‌های پروژه'));
    if (tab === 'members') api.get('/users?per_page=100').then(({ data }) => setUsers(data.data || [])).catch(() => toast.error('خطا در دریافت لیست کاربران'));
    if (tab === 'files') api.get(`/files?fileable_type=App\\Models\\Project&fileable_id=${id}`).then(({ data }) => setFiles(data.data || [])).catch(() => {});
    if (tab === 'meetings') api.get(`/meetings?project_id=${id}`).then(({ data }) => setMeetings(data.data || [])).catch(() => {});
    if (tab === 'activities') api.get(`/activity-logs?project_id=${id}`).then(({ data }) => setActivities(data.data || [])).catch(() => {});
  }, [tab, id]);

  if (loading) return <div className="page-container"><TableSkeleton rows={10} cols={3} /></div>;
  if (!project) return <div className="page-container"><EmptyState icon={Search} title="پروژه یافت نشد" /></div>;

  const tabs = [
    { key: 'overview', label: 'نمای کلی' },
    { key: 'tasks', label: 'تسک‌ها' },
    { key: 'backlog', label: 'بک‌لاگ‌ها' },
    { key: 'members', label: 'اعضا' },
    { key: 'files', label: 'فایل‌ها' },
    { key: 'meetings', label: 'جلسات' },
    { key: 'activities', label: 'فعالیت‌ها' },
  ];

  const fetchProjectFiles = () => {
    api.get(`/files?fileable_type=App\\Models\\Project&fileable_id=${id}`).then(({ data }) => setFiles(data.data || [])).catch(() => {});
  };

  const handleProjectFileUpload = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploading(true);
    const formData = new FormData();
    formData.append('file', file);
    formData.append('project_id', id);
    try {
      await api.post('/files', formData, { headers: { 'Content-Type': 'multipart/form-data' } });
      toast.success('فایل در پروژه آپلود شد');
      fetchProjectFiles();
    } catch (err) {
      toast.error(err.response?.data?.message || 'خطا در آپلود فایل');
    } finally {
      setUploading(false);
      if (fileInputRef.current) fileInputRef.current.value = '';
    }
  };

  const availableUsers = users.filter(user => !members.some(member => member.id === user.id));

  const handleAddMember = async (e) => {
    e.preventDefault();
    if (!selectedMemberId) return;
    setAddingMember(true);
    try {
      const { data } = await api.post(`/projects/${id}/members`, { user_id: Number(selectedMemberId) });
      const updatedProject = data.data;
      setProject(updatedProject);
      setMembers(updatedProject.members || []);
      setSelectedMemberId('');
      toast.success('عضو به پروژه اضافه شد');
    } catch (err) {
      toast.error(err.response?.data?.message || 'خطا در افزودن عضو');
    } finally {
      setAddingMember(false);
    }
  };

  const handleRemoveMember = async (memberId) => {
    setRemovingMemberId(memberId);
    try {
      await api.delete(`/projects/${id}/members/${memberId}`);
      setMembers(current => current.filter(member => member.id !== memberId));
      setProject(current => current ? {
        ...current,
        members: (current.members || []).filter(member => member.id !== memberId),
      } : current);
      toast.success('عضو از پروژه حذف شد');
    } catch (err) {
      toast.error(err.response?.data?.message || 'خطا در حذف عضو');
    } finally {
      setRemovingMemberId(null);
    }
  };

  return (
    <div className="page-container">
      <div className="card" style={{ marginBottom: '1.5rem' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '1rem' }}>
          <div>
            <h1 style={{ fontSize: '1.5rem', fontWeight: 700 }}>{project.title}</h1>
            <p style={{ color: 'var(--gray-500)', fontSize: '0.875rem', marginTop: '0.25rem' }}>{project.description || 'بدون توضیحات'}</p>
          </div>
          <div style={{ display: 'flex', gap: '0.5rem' }}>
            <StatusBadge status={project.status} />
            <PriorityBadge priority={project.priority} />
          </div>
        </div>
        <div className="progress-bar" style={{ marginBottom: '1rem' }}><div className="progress-fill" style={{ width: `${project.progress}%` }} /></div>
        <div style={{ display: 'flex', gap: '2rem', fontSize: '0.875rem', color: 'var(--gray-500)', flexWrap: 'wrap' }}>
          <div><strong>شروع:</strong> {formatJalaliDate(project.start_date)}</div>
          <div><strong>پایان:</strong> {formatJalaliDate(project.end_date)}</div>
          <div><strong>ریسک:</strong> {project.risk_level || '—'}</div>
          <div><strong>بودجه:</strong> {project.budget ? `${project.budget} تومان` : '—'}</div>
          <div><strong>ساعت تخمینی:</strong> {project.estimated_hours || '—'}</div>
          <div><strong>ساعت واقعی:</strong> {project.actual_hours || '—'}</div>
        </div>
      </div>

      <div className="tabs">
        {tabs.map(t => (
          <button key={t.key} className={`tab ${tab === t.key ? 'active' : ''}`} onClick={() => setTab(t.key)}>{t.label}</button>
        ))}
      </div>

      {tab === 'overview' && (
        <div className="grid grid-2">
          <div className="card">
            <h3 style={{ fontSize: '1rem', fontWeight: 600, marginBottom: '0.75rem' }}>خلاصه پروژه</h3>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem', fontSize: '0.875rem' }}>
              <div><strong>مشتری:</strong> {project.client || '—'}</div>
              <div><strong>مدیر پروژه:</strong> {project.project_manager?.name || '—'}</div>
              <div><strong>پیشرفت:</strong> {project.progress}%</div>
              <div><strong>برچسب‌ها:</strong> {project.tags?.length ? project.tags.join(', ') : '—'}</div>
            </div>
          </div>
          <div className="card">
            <h3 style={{ fontSize: '1rem', fontWeight: 600, marginBottom: '0.75rem' }}>اعضای تیم</h3>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.75rem' }}>
              {members?.map(m => (
                <div key={m.id} style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                  <div className="avatar avatar-sm">{m.name?.[0]}</div>
                  <span style={{ fontSize: '0.875rem' }}>{m.name}</span>
                </div>
              ))}
              {members.length === 0 && <span style={{ color: 'var(--gray-400)', fontSize: '0.875rem' }}>عضوی وجود ندارد</span>}
            </div>
          </div>
        </div>
      )}

      {tab === 'tasks' && (
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div className="table-container">
            <table>
              <thead><tr><th>عنوان</th><th>اولویت</th><th>وضعیت</th><th>تخصیص‌یافته به</th><th>ددلاین</th></tr></thead>
              <tbody>
                {tasks.length === 0 ? <tr><td colSpan={5}><EmptyState icon={CheckCircle} title="تسکی وجود ندارد" /></td></tr> :
                  tasks.map(t => (
                    <tr key={t.id}>
                      <td style={{ fontWeight: 500 }}>{t.title}</td>
                      <td><PriorityBadge priority={t.priority} /></td>
                      <td><StatusBadge status={t.status} /></td>
                      <td>{t.assignee?.name || '—'}</td>
                      <td style={{ color: isPastDate(t.due_date) && t.status !== 'done' ? 'var(--danger)' : 'inherit' }}>{formatJalaliDate(t.due_date)}</td>
                    </tr>
                  ))
                }
              </tbody>
            </table>
          </div>
        </div>
      )}

      {tab === 'backlog' && (
        <div className="card table-card">
          <div className="table-container">
            <table>
              <thead><tr><th>عنوان</th><th>نوع</th><th>اولویت</th><th>وضعیت</th><th>تسک مرتبط</th><th>تاریخ آرشیو</th></tr></thead>
              <tbody>
                {backlogItems.length === 0 ? <tr><td colSpan={6}><EmptyState icon={Archive} title="بک‌لاگی برای این پروژه وجود ندارد" /></td></tr> : backlogItems.map((item) => (
                  <tr key={item.id}>
                    <td><div className="backlog-title-cell"><strong>{item.title}</strong>{item.description && <small>{item.description}</small>}</div></td>
                    <td><span className="badge badge-info">{item.type}</span></td>
                    <td><PriorityBadge priority={item.priority} /></td>
                    <td><span className={`badge ${item.is_archived ? 'badge-gray' : 'badge-success'}`}>{item.is_archived ? 'تبدیل‌شده و آرشیوشده' : 'فعال و تبدیل‌نشده'}</span></td>
                    <td>{item.converted_task ? <div className="backlog-task-cell"><strong>{item.converted_task.title}</strong><small>{item.converted_task.assignee?.name || 'بدون مسئول'}</small></div> : '—'}</td>
                    <td>{item.archived_at ? formatJalaliDate(item.archived_at) : '—'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {tab === 'members' && (
        <>
          <form className="card" onSubmit={handleAddMember} style={{ display: 'flex', gap: '0.75rem', alignItems: 'flex-end', marginBottom: '1.5rem', flexWrap: 'wrap' }}>
            <div className="form-group" style={{ marginBottom: 0, flex: '1 1 260px' }}>
              <label className="form-label">افزودن عضو به پروژه</label>
              <FormSelect value={selectedMemberId} onChange={(e) => setSelectedMemberId(e.target.value)} disabled={addingMember || availableUsers.length === 0}>
                <option value="">{availableUsers.length === 0 ? 'همه کاربران عضو پروژه هستند' : 'انتخاب عضو'}</option>
                {availableUsers.map(user => (
                  <option key={user.id} value={user.id}>{user.name} - {user.email}</option>
                ))}
              </FormSelect>
            </div>
            <button className="btn btn-primary" type="submit" disabled={!selectedMemberId || addingMember}>
              <UserPlus size={16} />
              {addingMember ? 'در حال افزودن...' : 'افزودن عضو'}
            </button>
          </form>

          {members.length === 0 ? (
            <div className="card"><EmptyState icon={Users} title="عضوی وجود ندارد" /></div>
          ) : (
            <div className="grid grid-3">
              {members.map(m => (
                <div key={m.id} className="card" style={{ display: 'flex', alignItems: 'center', gap: '1rem', justifyContent: 'space-between' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '1rem', minWidth: 0 }}>
                  <div className="avatar avatar-lg">{m.name?.[0]}</div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontWeight: 600 }}>{m.name}</div>
                    <div style={{ fontSize: '0.8125rem', color: 'var(--gray-500)' }}>{m.job_title || '—'}</div>
                    <div style={{ fontSize: '0.75rem', color: 'var(--gray-400)' }}>{m.email}</div>
                  </div>
                  </div>
                  <button
                    className="btn btn-danger btn-sm"
                    type="button"
                    disabled={removingMemberId === m.id}
                    onClick={() => handleRemoveMember(m.id)}
                    title="حذف عضو"
                    style={{ padding: '0.375rem', flexShrink: 0 }}
                  >
                    <Trash2 size={16} />
                  </button>
                </div>
              ))}
            </div>
          )}
        </>
      )}

      {tab === 'files' && (
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '1rem', borderBottom: '1px solid var(--gray-100)' }}>
            <strong>فایل‌های پروژه</strong>
            <div>
              <input ref={fileInputRef} type="file" onChange={handleProjectFileUpload} style={{ display: 'none' }} />
              <button className="btn btn-primary btn-sm" disabled={uploading} onClick={() => fileInputRef.current?.click()}>
                {uploading ? 'در حال آپلود...' : 'آپلود در پروژه'}
              </button>
            </div>
          </div>
          <div className="table-container">
            <table>
              <thead><tr><th>نام فایل</th><th>نوع</th><th>حجم</th><th>آپلودکننده</th><th>تاریخ</th></tr></thead>
              <tbody>
                {files.length === 0 ? <tr><td colSpan={5}><EmptyState icon={Paperclip} title="فایلی وجود ندارد" /></td></tr> :
                  files.map(f => (
                    <tr key={f.id}>
                      <td>{f.original_name}</td>
                      <td><span className="badge badge-gray">{f.mime_type}</span></td>
                      <td>{(f.size / 1024).toFixed(1)} KB</td>
                      <td>{f.user?.name || '—'}</td>
                      <td>{formatJalaliDate(f.created_at)}</td>
                    </tr>
                  ))
                }
              </tbody>
            </table>
          </div>
        </div>
      )}

      {tab === 'meetings' && (
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div className="table-container">
            <table>
              <thead><tr><th>عنوان</th><th>تاریخ</th><th>نوع</th><th>ساعت</th><th>مکان</th></tr></thead>
              <tbody>
                {meetings.length === 0 ? <tr><td colSpan={5}><EmptyState icon={Calendar} title="جلسه‌ای وجود ندارد" /></td></tr> :
                  meetings.map(m => (
                    <tr key={m.id}>
                      <td style={{ fontWeight: 500 }}>{m.title}</td>
                      <td>{formatJalaliDate(m.date)}</td>
                      <td><span className="badge badge-info">{m.meeting_type}</span></td>
                      <td>{m.start_time?.slice(0, 5)} - {m.end_time?.slice(0, 5)}</td>
                      <td>{m.location || 'آنلاین'}</td>
                    </tr>
                  ))
                }
              </tbody>
            </table>
          </div>
        </div>
      )}

      {tab === 'activities' && (
        <div className="card">
          {activities.length === 0 ? <EmptyState icon={FileText} title="فعالیتی وجود ندارد" /> :
            activities.map((a, i) => (
              <div key={a.id} style={{ display: 'flex', gap: '0.75rem', padding: '0.75rem 0', borderBottom: i < activities.length - 1 ? '1px solid var(--gray-100)' : 'none' }}>
                <div className="avatar avatar-sm">{a.user?.name?.[0] || '?'}</div>
                <div>
                  <div style={{ fontSize: '0.875rem' }}>{a.description}</div>
                  <div style={{ fontSize: '0.75rem', color: 'var(--gray-400)' }}>{formatJalaliDateTime(a.created_at)}</div>
                </div>
              </div>
            ))
          }
        </div>
      )}
    </div>
  );
}
