import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import api from '../services/api';
import StatusBadge from '../components/StatusBadge';
import PriorityBadge from '../components/PriorityBadge';
import Modal from '../components/Modal';
import ConfirmDialog from '../components/ConfirmDialog';
import EmptyState from '../components/EmptyState';
import FormSelect from '../components/FormSelect';
import PersianDateInput from '../components/PersianDateInput';
import { TableSkeleton } from '../components/LoadingSkeleton';
import toast from 'react-hot-toast';
import { Folder, Layout, CreditCard, Edit3, Archive, Trash2 } from 'lucide-react';
import { formatJalaliDate, isPastDate } from '../utils/date';

export default function Projects() {
  const [projects, setProjects] = useState([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [priorityFilter, setPriorityFilter] = useState('');
  const [showModal, setShowModal] = useState(false);
  const [editing, setEditing] = useState(null);
  const [deleting, setDeleting] = useState(null);
  const [viewMode, setViewMode] = useState('table');
  const [meta, setMeta] = useState({});
  const [page, setPage] = useState(1);
  const [users, setUsers] = useState([]);
  const [departments, setDepartments] = useState([]);

  const [form, setForm] = useState({ title: '', description: '', client: '', priority: 'medium', status: 'planning', start_date: '', end_date: '', project_manager_id: '', department_id: '', budget: '', estimated_hours: '', risk_level: 'low' });
  const [saving, setSaving] = useState(false);

  const fetchProjects = () => {
    setLoading(true);
    const params = { page, per_page: 15, search: search || undefined, status: statusFilter || undefined, priority: priorityFilter || undefined };
    api.get('/projects', { params }).then(({ data }) => {
      setProjects(data.data);
      setMeta(data.meta || {});
    }).catch(() => toast.error('خطا در دریافت پروژه‌ها'))
    .finally(() => setLoading(false));
  };

  useEffect(() => { fetchProjects(); }, [page, statusFilter, priorityFilter]);
  useEffect(() => { if (search !== undefined) { const t = setTimeout(() => { setPage(1); fetchProjects(); }, 300); return () => clearTimeout(t); } }, [search]);

  useEffect(() => {
    api.get('/users', { params: { per_page: 100 } }).then(({ data }) => setUsers(data.data || [])).catch(() => {});
    api.get('/departments').then(({ data }) => setDepartments(data.flat || [])).catch(() => {});
  }, []);

  const openCreate = () => {
    setEditing(null);
    setForm({ title: '', description: '', client: '', priority: 'medium', status: 'planning', start_date: '', end_date: '', project_manager_id: '', department_id: '', budget: '', estimated_hours: '', risk_level: 'low' });
    setShowModal(true);
  };

  const openEdit = (project) => {
    setEditing(project);
    setForm({
      title: project.title, description: project.description || '', client: project.client || '',
      priority: project.priority, status: project.status, start_date: project.start_date || '',
      end_date: project.end_date || '', project_manager_id: project.project_manager_id || '',
      department_id: project.department_id || '',
      budget: project.budget || '', estimated_hours: project.estimated_hours || '', risk_level: project.risk_level || 'low',
    });
    setShowModal(true);
  };

  const handleSave = async (e) => {
    e.preventDefault();
    if (!form.title) { toast.error('عنوان پروژه الزامی است'); return; }
    setSaving(true);
    try {
      if (editing) {
        await api.put(`/projects/${editing.id}`, form);
        toast.success('پروژه با موفقیت به‌روزرسانی شد');
      } else {
        await api.post('/projects', form);
        toast.success('پروژه با موفقیت ایجاد شد');
      }
      setShowModal(false);
      fetchProjects();
    } catch (err) { toast.error(err.response?.data?.message || 'خطا در ذخیره پروژه'); }
    finally { setSaving(false); }
  };

  const handleDelete = async () => {
    try {
      await api.delete(`/projects/${deleting.id}`);
      toast.success('پروژه حذف شد');
      setDeleting(null);
      fetchProjects();
    } catch (err) { toast.error('خطا در حذف پروژه'); }
  };

  const handleArchive = async (project) => {
    try {
      await api.post(`/projects/${project.id}/archive`);
      toast.success('پروژه بایگانی شد');
      fetchProjects();
    } catch (err) { toast.error('خطا در بایگانی پروژه'); }
  };

  return (
    <div className="page-container">
      <div className="page-header">
        <button className="btn btn-primary" onClick={openCreate}>+ پروژه جدید</button>
      </div>
      <div className="filter-bar">
        <input className="form-input" placeholder="جستجوی پروژه..." value={search} onChange={e => setSearch(e.target.value)} style={{ maxWidth: 280 }} />
        <select className="form-select" value={statusFilter} onChange={e => { setStatusFilter(e.target.value); setPage(1); }}>
          <option value="">همه وضعیت‌ها</option>
          <option value="planning">برنامه‌ریزی</option>
          <option value="in_progress">در حال انجام</option>
          <option value="waiting">در انتظار</option>
          <option value="suspended">متوقف‌شده</option>
          <option value="completed">تکمیل‌شده</option>
          <option value="cancelled">لغوشده</option>
        </select>
        <select className="form-select" value={priorityFilter} onChange={e => { setPriorityFilter(e.target.value); setPage(1); }}>
          <option value="">همه اولویت‌ها</option>
          <option value="low">کم</option>
          <option value="medium">متوسط</option>
          <option value="high">زیاد</option>
          <option value="critical">بحرانی</option>
        </select>
        <div style={{ display: 'flex', gap: '0.25rem', background: 'var(--gray-100)', borderRadius: 'var(--radius-sm)', padding: '2px' }}>
          <button className={`btn btn-sm ${viewMode === 'table' ? 'btn-primary' : 'btn-secondary'}`} onClick={() => setViewMode('table')}><Layout size={16} /></button>
          <button className={`btn btn-sm ${viewMode === 'card' ? 'btn-primary' : 'btn-secondary'}`} onClick={() => setViewMode('card')}><CreditCard size={16} /></button>
        </div>
      </div>

      {loading ? <TableSkeleton rows={8} cols={6} /> : projects.length === 0 ? (
        <EmptyState icon={Folder} title="پروژه‌ای یافت نشد" description="هنوز هیچ پروژه‌ای ایجاد نشده است" action={<button className="btn btn-primary" onClick={openCreate}>ایجاد پروژه جدید</button>} />
      ) : viewMode === 'table' ? (
        <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>
                  <th>ددلاین</th>
                  <th>عملیات</th>
                </tr>
              </thead>
              <tbody>
                {projects.map(p => (
                  <tr key={p.id}>
                    <td><Link to={`/projects/${p.id}`} style={{ fontWeight: 500, color: 'var(--primary)' }}>{p.title}</Link></td>
                    <td><StatusBadge status={p.status} /></td>
                    <td><PriorityBadge priority={p.priority} /></td>
                    <td style={{ minWidth: 120 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                        <div className="progress-bar" style={{ flex: 1 }}><div className="progress-fill" style={{ width: `${p.progress}%` }} /></div>
                        <span style={{ fontSize: '0.8125rem', fontWeight: 600 }}>{p.progress}%</span>
                      </div>
                    </td>
                    <td>{p.project_manager?.name || '—'}</td>
                    <td style={{ fontSize: '0.875rem', color: isPastDate(p.end_date) && p.status !== 'completed' ? 'var(--danger)' : 'inherit' }}>{formatJalaliDate(p.end_date)}</td>
                    <td>
                      <div style={{ display: 'flex', gap: '0.25rem' }}>
                        <button className="btn btn-sm btn-secondary" onClick={() => openEdit(p)}><Edit3 size={14} /></button>
                        <button className="btn btn-sm btn-secondary" onClick={() => handleArchive(p)}><Archive size={14} /></button>
                        <button className="btn btn-sm btn-danger" onClick={() => setDeleting(p)}><Trash2 size={14} /></button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          {meta?.last_page > 1 && (
            <div style={{ display: 'flex', justifyContent: 'center', gap: '0.5rem', padding: '1rem', borderTop: '1px solid var(--gray-100)' }}>
              {Array.from({ length: meta.last_page }, (_, i) => i + 1).map(p => (
                <button key={p} className={`btn btn-sm ${page === p ? 'btn-primary' : 'btn-secondary'}`} onClick={() => setPage(p)}>{p}</button>
              ))}
            </div>
          )}
        </div>
      ) : (
        <div className="grid grid-3">
          {projects.map(p => (
            <div key={p.id} className="card">
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '0.75rem' }}>
                <Link to={`/projects/${p.id}`} style={{ fontWeight: 600, color: 'var(--gray-900)' }}>{p.title}</Link>
                <StatusBadge status={p.status} />
              </div>
              <p style={{ fontSize: '0.8125rem', color: 'var(--gray-500)', marginBottom: '0.75rem', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{p.description || '—'}</p>
              <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center', marginBottom: '0.75rem' }}>
                <PriorityBadge priority={p.priority} />
                {p.risk_level && <span className="badge badge-gray">ریسک: {p.risk_level}</span>}
              </div>
              <div className="progress-bar" style={{ marginBottom: '0.5rem' }}><div className="progress-fill" style={{ width: `${p.progress}%` }} /></div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '0.75rem', color: 'var(--gray-400)' }}>
                <span>{formatJalaliDate(p.end_date, 'بدون ددلاین')}</span>
                <span>{(p.tasks_count || 0)} تسک</span>
              </div>
            </div>
          ))}
        </div>
      )}

      {showModal && (
        <Modal title={editing ? 'ویرایش پروژه' : 'پروژه جدید'} onClose={() => setShowModal(false)} footer={
          <>
            <button className="btn btn-secondary" onClick={() => setShowModal(false)}>انصراف</button>
            <button className="btn btn-primary" onClick={handleSave} disabled={saving}>{saving ? 'در حال ذخیره...' : 'ذخیره'}</button>
          </>
        } size="xl">
          <form onSubmit={handleSave} className="project-modal-form">
            <div className="project-modal-grid">
              <div className="form-group">
                <label className="form-label">عنوان پروژه *</label>
                <input className="form-input" value={form.title} onChange={e => setForm({...form, title: e.target.value})} />
              </div>
              <div className="form-group wide">
                <label className="form-label">توضیحات</label>
                <textarea className="form-textarea" value={form.description} onChange={e => setForm({...form, description: e.target.value})} />
              </div>
              <div className="form-group">
                <label className="form-label">مشتری</label>
                <input className="form-input" value={form.client} onChange={e => setForm({...form, client: e.target.value})} />
              </div>
              <div className="form-group">
                <label className="form-label">مدیر پروژه</label>
                <select className="form-select" value={form.project_manager_id} onChange={e => setForm({...form, project_manager_id: e.target.value})}>
                  <option value="">انتخاب کنید</option>
                  {users.map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
                </select>
              </div>
              <div className="form-group">
                <label className="form-label">اتصال سازمانی</label>
                <FormSelect value={form.department_id} onChange={e => setForm({...form, department_id: e.target.value})}>
                  <option value="">بدون اتصال</option>
                  {departments.map(d => <option key={d.id} value={d.id}>{d.name}</option>)}
                </FormSelect>
              </div>
              <div className="form-group">
                <label className="form-label">اولویت</label>
                <select className="form-select" value={form.priority} onChange={e => setForm({...form, priority: e.target.value})}>
                  <option value="low">کم</option>
                  <option value="medium">متوسط</option>
                  <option value="high">زیاد</option>
                  <option value="critical">بحرانی</option>
                </select>
              </div>
              <div className="form-group">
                <label className="form-label">وضعیت</label>
                <select className="form-select" value={form.status} onChange={e => setForm({...form, status: e.target.value})}>
                  <option value="planning">برنامه‌ریزی</option>
                  <option value="in_progress">در حال انجام</option>
                  <option value="waiting">در انتظار</option>
                  <option value="suspended">متوقف‌شده</option>
                  <option value="completed">تکمیل‌شده</option>
                  <option value="cancelled">لغوشده</option>
                </select>
              </div>
              <div className="form-group">
                <label className="form-label">تاریخ شروع</label>
                <PersianDateInput value={form.start_date} onChange={value => setForm({...form, start_date: value})} />
              </div>
              <div className="form-group">
                <label className="form-label">تاریخ پایان</label>
                <PersianDateInput value={form.end_date} onChange={value => setForm({...form, end_date: value})} />
              </div>
              <div className="form-group">
                <label className="form-label">بودجه</label>
                <input className="form-input" type="number" value={form.budget} onChange={e => setForm({...form, budget: e.target.value})} />
              </div>
              <div className="form-group">
                <label className="form-label">ساعت تخمینی</label>
                <input className="form-input" type="number" value={form.estimated_hours} onChange={e => setForm({...form, estimated_hours: e.target.value})} />
              </div>
              <div className="form-group">
                <label className="form-label">سطح ریسک</label>
                <select className="form-select" value={form.risk_level} onChange={e => setForm({...form, risk_level: e.target.value})}>
                  <option value="low">کم</option>
                  <option value="medium">متوسط</option>
                  <option value="high">زیاد</option>
                </select>
              </div>
            </div>
          </form>
        </Modal>
      )}

      {deleting && <ConfirmDialog title="حذف پروژه" message={`آیا از حذف "${deleting.title}" اطمینان دارید؟`} onConfirm={handleDelete} onCancel={() => setDeleting(null)} danger />}
    </div>
  );
}
