import { useState, useEffect } from 'react';
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 { TableSkeleton } from '../components/LoadingSkeleton';
import PersianDateInput from '../components/PersianDateInput';
import toast from 'react-hot-toast';
import { CheckCircle, Edit3, Trash2 } from 'lucide-react';
import { formatJalaliDate, isPastDate } from '../utils/date';

export default function Tasks() {
  const [tasks, setTasks] = useState([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [filters, setFilters] = useState({ status: '', priority: '', project_id: '', my: false, delayed: false });
  const [showModal, setShowModal] = useState(false);
  const [editing, setEditing] = useState(null);
  const [deleting, setDeleting] = useState(null);
  const [detailTask, setDetailTask] = useState(null);
  const [meta, setMeta] = useState({});
  const [page, setPage] = useState(1);
  const [projects, setProjects] = useState([]);
  const [users, setUsers] = useState([]);
  const [saving, setSaving] = useState(false);

  const [form, setForm] = useState({ title: '', description: '', project_id: '', assignee_id: '', priority: 'medium', status: 'todo', start_date: '', due_date: '', estimated_time: '' });

  const fetchTasks = () => {
    setLoading(true);
    const params = { page, per_page: 15, search: search || undefined, ...filters };
    Object.keys(params).forEach(k => { if (!params[k]) delete params[k]; });
    const url = filters.my ? '/my-tasks' : filters.delayed ? '/delayed-tasks' : '/tasks';
    api.get(url, { params }).then(({ data }) => {
      setTasks(data.data || []);
      setMeta(data.meta || {});
    }).catch(() => toast.error('خطا در دریافت تسک‌ها'))
    .finally(() => setLoading(false));
  };

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

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

  const openCreate = () => {
    setEditing(null);
    setForm({ title: '', description: '', project_id: '', assignee_id: '', priority: 'medium', status: 'todo', start_date: '', due_date: '', estimated_time: '' });
    setShowModal(true);
  };

  const openEdit = (task) => {
    setEditing(task);
    setForm({
      title: task.title, description: task.description || '', project_id: task.project_id || '',
      assignee_id: task.assignee_id || '', priority: task.priority, status: task.status,
      start_date: task.start_date || '', due_date: task.due_date || '', estimated_time: task.estimated_time || '',
    });
    setShowModal(true);
  };

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

  const handleDelete = async () => {
    try { await api.delete(`/tasks/${deleting.id}`); toast.success('تسک حذف شد'); setDeleting(null); fetchTasks(); }
    catch { toast.error('خطا در حذف'); }
  };

  const updateStatus = async (task, status) => {
    try {
      await api.put(`/tasks/${task.id}/status`, { status });
      toast.success('وضعیت به‌روزرسانی شد');
      fetchTasks();
    } catch { 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={filters.status} onChange={e => { setFilters({...filters, status: e.target.value}); setPage(1); }}>
          <option value="">همه وضعیت‌ها</option>
          <option value="todo">برای انجام</option>
          <option value="in_progress">در حال انجام</option>
          <option value="waiting">در انتظار</option>
          <option value="review">نیازمند بررسی</option>
          <option value="done">انجام‌شده</option>
        </select>
        <select className="form-select" value={filters.priority} onChange={e => { setFilters({...filters, priority: e.target.value}); setPage(1); }}>
          <option value="">همه اولویت‌ها</option>
          <option value="low">کم</option>
          <option value="medium">متوسط</option>
          <option value="high">زیاد</option>
          <option value="urgent">فوری</option>
        </select>
        <select className="form-select" value={filters.project_id} onChange={e => { setFilters({...filters, project_id: e.target.value}); setPage(1); }}>
          <option value="">همه پروژه‌ها</option>
          {projects.map(p => <option key={p.id} value={p.id}>{p.title}</option>)}
        </select>
        <button className={`btn btn-sm ${filters.my ? 'btn-primary' : 'btn-secondary'}`} onClick={() => { setFilters({...filters, my: !filters.my}); setPage(1); }}>تسک‌های من</button>
        <button className={`btn btn-sm ${filters.delayed ? 'btn-danger' : 'btn-secondary'}`} onClick={() => { setFilters({...filters, delayed: !filters.delayed}); setPage(1); }}>عقب‌افتاده</button>
      </div>

      {loading ? <TableSkeleton rows={8} cols={6} /> : tasks.length === 0 ? (
        <EmptyState icon={CheckCircle} title="تسکی یافت نشد" description="هیچ تسکی با این فیلترها وجود ندارد" action={<button className="btn btn-primary" onClick={openCreate}>ایجاد تسک جدید</button>} />
      ) : (
        <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>
                {tasks.map(t => (
                  <tr key={t.id} onClick={() => setDetailTask(t)} style={{ cursor: 'pointer' }}>
                    <td style={{ fontWeight: 500 }}>{t.title}</td>
                    <td style={{ fontSize: '0.875rem', color: 'var(--gray-500)' }}>{t.project?.title || '—'}</td>
                    <td><PriorityBadge priority={t.priority} /></td>
                    <td>
                      <select className="form-select" style={{ width: 'auto', padding: '0.25rem 0.5rem', fontSize: '0.8125rem' }} value={t.status} onClick={e => e.stopPropagation()} onChange={e => updateStatus(t, e.target.value)}>
                        <option value="todo">برای انجام</option>
                        <option value="in_progress">در حال انجام</option>
                        <option value="waiting">در انتظار</option>
                        <option value="review">نیازمند بررسی</option>
                        <option value="done">انجام‌شده</option>
                      </select>
                    </td>
                    <td>{t.assignee?.name || '—'}</td>
                    <td style={{ color: isPastDate(t.due_date) && t.status !== 'done' ? 'var(--danger)' : 'inherit' }}>{formatJalaliDate(t.due_date)}</td>
                    <td>
                      <div style={{ display: 'flex', gap: '0.25rem' }} onClick={e => e.stopPropagation()}>
                        <button className="btn btn-sm btn-secondary" onClick={() => openEdit(t)}><Edit3 size={14} /></button>
                        <button className="btn btn-sm btn-danger" onClick={() => setDeleting(t)}><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>
      )}

      {showModal && (
        <Modal title={editing ? 'ویرایش تسک' : 'تسک جدید'} onClose={() => setShowModal(false)} size="xl" footer={
          <><button className="btn btn-secondary" onClick={() => setShowModal(false)}>انصراف</button><button className="btn btn-primary" onClick={handleSave} disabled={saving}>{saving ? 'در حال ذخیره...' : 'ذخیره'}</button></>
        }>
          <form onSubmit={handleSave} className="compact-modal-form">
            <div className="compact-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>
                <select className="form-select" value={form.project_id} onChange={e => setForm({...form, project_id: e.target.value})}>
                  <option value="">انتخاب کنید</option>
                  {projects.map(p => <option key={p.id} value={p.id}>{p.title}</option>)}
                </select>
              </div>
              <div className="form-group"><label className="form-label">تخصیص به</label>
                <select className="form-select" value={form.assignee_id} onChange={e => setForm({...form, assignee_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>
                <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="urgent">فوری</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="todo">برای انجام</option>
                  <option value="in_progress">در حال انجام</option>
                  <option value="waiting">در انتظار</option>
                  <option value="review">نیازمند بررسی</option>
                  <option value="done">انجام‌شده</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.due_date} onChange={value => setForm({...form, due_date: value})} /></div>
              <div className="form-group"><label className="form-label">زمان تخمینی (ساعت)</label><input className="form-input" type="number" value={form.estimated_time} onChange={e => setForm({...form, estimated_time: e.target.value})} /></div>
            </div>
          </form>
        </Modal>
      )}

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

      {detailTask && (
        <>
          <div className="drawer-overlay" onClick={() => setDetailTask(null)} />
          <div className="drawer">
            <div className="drawer-header">
              <h3 className="drawer-title">{detailTask.title}</h3>
              <button className="modal-close" onClick={() => setDetailTask(null)}>&times;</button>
            </div>
            <div className="drawer-body">
              <div style={{ display: 'flex', gap: '0.5rem', marginBottom: '1rem' }}>
                <StatusBadge status={detailTask.status} />
                <PriorityBadge priority={detailTask.priority} />
              </div>
              <p style={{ fontSize: '0.875rem', color: 'var(--gray-600)', marginBottom: '1rem' }}>{detailTask.description || 'بدون توضیحات'}</p>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.75rem', fontSize: '0.875rem', marginBottom: '1rem' }}>
                <div><strong>پروژه:</strong> {detailTask.project?.title || '—'}</div>
                <div><strong>تخصیص‌یافته:</strong> {detailTask.assignee?.name || '—'}</div>
                <div><strong>تاریخ شروع:</strong> {formatJalaliDate(detailTask.start_date)}</div>
                <div><strong>ددلاین:</strong> {formatJalaliDate(detailTask.due_date)}</div>
                <div><strong>زمان تخمینی:</strong> {detailTask.estimated_time || '—'} ساعت</div>
                <div><strong>زمان واقعی:</strong> {detailTask.actual_time || '—'} ساعت</div>
              </div>

              <h4 style={{ fontSize: '0.9375rem', fontWeight: 600, marginBottom: '0.75rem', marginTop: '1rem' }}>نظرات</h4>
              <CommentsSection taskId={detailTask.id} />

              <h4 style={{ fontSize: '0.9375rem', fontWeight: 600, marginBottom: '0.75rem', marginTop: '1rem' }}>چک‌لیست</h4>
              <ChecklistSection taskId={detailTask.id} />
            </div>
          </div>
        </>
      )}
    </div>
  );
}

function CommentsSection({ taskId }) {
  const [comments, setComments] = useState([]);
  const [body, setBody] = useState('');
  const [loadingC, setLoadingC] = useState(true);

  useEffect(() => {
    api.get(`/comments?commentable_type=App\\Models\\Task&commentable_id=${taskId}`).then(({ data }) => setComments(data.data || [])).catch(() => {}).finally(() => setLoadingC(false));
  }, [taskId]);

  const addComment = async () => {
    if (!body.trim()) return;
    try {
      const { data } = await api.post('/comments', { body, commentable_type: 'App\\Models\\Task', commentable_id: taskId });
      setComments([data.data, ...comments]);
      setBody('');
      toast.success('نظر اضافه شد');
    } catch { toast.error('خطا'); }
  };

  return (
    <div>
      <div style={{ display: 'flex', gap: '0.5rem', marginBottom: '1rem' }}>
        <textarea className="form-textarea" style={{ minHeight: 60, flex: 1 }} value={body} onChange={e => setBody(e.target.value)} placeholder="نظر خود را بنویسید..." />
        <button className="btn btn-primary btn-sm" onClick={addComment} style={{ alignSelf: 'flex-end' }}>ارسال</button>
      </div>
      {loadingC ? <div className="skeleton" style={{ height: 40, marginBottom: 8 }} /> :
        comments.map(c => (
          <div key={c.id} style={{ padding: '0.5rem 0', borderBottom: '1px solid var(--gray-50)' }}>
            <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center', marginBottom: '0.25rem' }}>
              <div className="avatar avatar-sm" style={{ width: 24, height: 24, fontSize: '0.625rem' }}>{c.user?.name?.[0] || '?'}</div>
              <span style={{ fontSize: '0.8125rem', fontWeight: 500 }}>{c.user?.name}</span>
              <span style={{ fontSize: '0.75rem', color: 'var(--gray-400)' }}>{formatJalaliDate(c.created_at)}</span>
            </div>
            <p style={{ fontSize: '0.875rem', color: 'var(--gray-600)', marginRight: '2rem' }}>{c.body}</p>
          </div>
        ))
      }
    </div>
  );
}

function ChecklistSection({ taskId }) {
  const [items, setItems] = useState([]);
  const [title, setTitle] = useState('');

  useEffect(() => {
    api.get(`/tasks/${taskId}/checklists`).then(({ data }) => setItems(data.data || [])).catch(() => {});
  }, [taskId]);

  const addItem = async () => {
    if (!title.trim()) return;
    try {
      const { data } = await api.post(`/tasks/${taskId}/checklists`, { title });
      setItems([...items, data.data]);
      setTitle('');
    } catch { toast.error('خطا'); }
  };

  const toggle = async (item) => {
    try {
      await api.put(`/checklists/${item.id}/toggle`);
      setItems(items.map(i => i.id === item.id ? { ...i, is_completed: !i.is_completed } : i));
    } catch { toast.error('خطا'); }
  };

  return (
    <div>
      <div style={{ display: 'flex', gap: '0.5rem', marginBottom: '0.75rem' }}>
        <input className="form-input" value={title} onChange={e => setTitle(e.target.value)} placeholder="مورد جدید..." style={{ flex: 1 }} />
        <button className="btn btn-primary btn-sm" onClick={addItem}>افزودن</button>
      </div>
      {items.map(item => (
        <div key={item.id} style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', padding: '0.375rem 0' }}>
          <input type="checkbox" checked={!!item.is_completed} onChange={() => toggle(item)} style={{ width: 18, height: 18 }} />
          <span style={{ fontSize: '0.875rem', textDecoration: item.is_completed ? 'line-through' : 'none', color: item.is_completed ? 'var(--gray-400)' : 'var(--gray-700)' }}>{item.title}</span>
        </div>
      ))}
    </div>
  );
}
