import { useState, useEffect } from 'react';
import api from '../services/api';
import StatusBadge from '../components/StatusBadge';
import PriorityBadge from '../components/PriorityBadge';
import EmptyState from '../components/EmptyState';
import Modal from '../components/Modal';
import FormSelect from '../components/FormSelect';
import toast from 'react-hot-toast';
import { MessageSquare, Save } from 'lucide-react';
import { formatJalaliDate, isPastDate } from '../utils/date';

const columns = [
  { key: 'todo', label: 'برای انجام', color: '#94a3b8' },
  { key: 'in_progress', label: 'در حال انجام', color: '#6366f1' },
  { key: 'waiting', label: 'در انتظار', color: '#f59e0b' },
  { key: 'review', label: 'نیازمند بررسی', color: '#3b82f6' },
  { key: 'done', label: 'انجام‌شده', color: '#22c55e' },
];
const blockerOptions = [
  { value: '', label: 'بدون بلاکر' },
  { value: 'manager_review', label: 'منتظر بررسی مدیر' },
  { value: 'dependency', label: 'وابسته به تسک دیگر' },
  { value: 'missing_info', label: 'نیازمند اطلاعات بیشتر' },
  { value: 'technical_issue', label: 'مشکل فنی' },
  { value: 'waiting_for_person', label: 'منتظر همکاری فرد دیگر' },
  { value: 'other', label: 'سایر' },
];

export default function Kanban() {
  const [board, setBoard] = useState({});
  const [loading, setLoading] = useState(true);
  const [filters, setFilters] = useState({ project_id: '', assignee_id: '', priority: '' });
  const [projects, setProjects] = useState([]);
  const [users, setUsers] = useState([]);
  const [draggedTask, setDraggedTask] = useState(null);
  const [newTask, setNewTask] = useState({ column: '', title: '' });
  const [selectedTask, setSelectedTask] = useState(null);
  const [comments, setComments] = useState([]);
  const [detailLoading, setDetailLoading] = useState(false);
  const [noteForm, setNoteForm] = useState({ body: '', mentioned_user_id: '' });
  const [blockerForm, setBlockerForm] = useState({ blocker_type: '', blocker_note: '' });
  const [savingDetail, setSavingDetail] = useState(false);
  const [detailStep, setDetailStep] = useState(0);
  const [commentIndex, setCommentIndex] = useState(0);

  const fetchBoard = () => {
    setLoading(true);
    const params = {};
    if (filters.project_id) params.project_id = filters.project_id;
    if (filters.assignee_id) params.assignee_id = filters.assignee_id;
    if (filters.priority) params.priority = filters.priority;
    api.get('/tasks', { params }).then(({ data }) => {
      const items = data.data || [];
      const grouped = {};
      columns.forEach(c => { grouped[c.key] = []; });
      items.forEach(t => {
        if (grouped[t.status]) grouped[t.status].push(t);
        else grouped['todo'].push(t);
      });
      setBoard(grouped);
    }).catch(() => toast.error('خطا در دریافت تسک‌ها'))
    .finally(() => setLoading(false));
  };

  useEffect(() => { fetchBoard(); }, [filters]);

  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 handleDragStart = (task, column) => {
    setDraggedTask({ ...task, fromColumn: column });
  };

  const handleDrop = async (toColumn) => {
    if (!draggedTask || draggedTask.fromColumn === toColumn) { setDraggedTask(null); return; }
    const updated = { ...board };
    updated[draggedTask.fromColumn] = updated[draggedTask.fromColumn].filter(t => t.id !== draggedTask.id);
    updated[toColumn] = [{ ...draggedTask, status: toColumn }, ...updated[toColumn]];
    setBoard(updated);
    setDraggedTask(null);
    try {
      await api.put(`/tasks/${draggedTask.id}/status`, { status: toColumn });
    } catch {
      toast.error('خطا در به‌روزرسانی وضعیت');
      fetchBoard();
    }
  };

  const handleAddTask = async (column) => {
    if (!newTask.title.trim()) return;
    try {
      await api.post('/tasks', { title: newTask.title, status: column, project_id: filters.project_id || undefined });
      toast.success('تسک ایجاد شد');
      setNewTask({ column: '', title: '' });
      fetchBoard();
    } catch { toast.error('خطا'); }
  };

  const openTaskDetail = async (task) => {
    setSelectedTask(task);
    setDetailStep(0);
    setCommentIndex(0);
    setBlockerForm({ blocker_type: task.blocker_type || '', blocker_note: task.blocker_note || '' });
    setNoteForm({ body: '', mentioned_user_id: '' });
    setDetailLoading(true);
    try {
      const [taskRes, commentsRes] = await Promise.all([
        api.get(`/tasks/${task.id}`),
        api.get('/comments', { params: { commentable_type: 'App\\Models\\Task', commentable_id: task.id, per_page: 30 } }),
      ]);
      const fullTask = taskRes.data.data || task;
      setSelectedTask(fullTask);
      setBlockerForm({ blocker_type: fullTask.blocker_type || '', blocker_note: fullTask.blocker_note || '' });
      setComments(commentsRes.data.data || []);
    } catch {
      toast.error('خطا در دریافت جزئیات تسک');
    } finally {
      setDetailLoading(false);
    }
  };

  const saveBlocker = async () => {
    if (!selectedTask) return;
    setSavingDetail(true);
    try {
      const { data } = await api.put(`/tasks/${selectedTask.id}`, blockerForm);
      const updatedTask = data.data || { ...selectedTask, ...blockerForm };
      setSelectedTask(updatedTask);
      setBoard((current) => {
        const next = { ...current };
        Object.keys(next).forEach((key) => {
          next[key] = next[key].map((task) => task.id === selectedTask.id ? { ...task, ...updatedTask } : task);
        });
        return next;
      });
      toast.success('بلاکر تسک ذخیره شد');
    } catch {
      toast.error('خطا در ذخیره بلاکر');
    } finally {
      setSavingDetail(false);
    }
  };

  const addNote = async (e) => {
    e.preventDefault();
    if (!selectedTask || !noteForm.body.trim()) return;
    setSavingDetail(true);
    try {
      const { data } = await api.post('/comments', {
        body: noteForm.body,
        mentioned_user_id: noteForm.mentioned_user_id || undefined,
        commentable_type: 'App\\Models\\Task',
        commentable_id: selectedTask.id,
      });
      setComments((current) => [data.data, ...current]);
      setNoteForm({ body: '', mentioned_user_id: '' });
      toast.success(noteForm.mentioned_user_id ? 'نوت ثبت شد و اعلان ارسال شد' : 'نوت ثبت شد');
      fetchBoard();
    } catch {
      toast.error('خطا در ثبت نوت');
    } finally {
      setSavingDetail(false);
    }
  };

  return (
    <div className="page-container" style={{ maxWidth: '100%', padding: '1rem 0.75rem' }}>
      <div className="page-header" style={{ padding: '0 0 0.75rem 0', marginBottom: '0.75rem' }}>
      </div>
      <div className="filter-bar" style={{ flexWrap: 'nowrap' }}>
        <select className="form-select" value={filters.project_id} onChange={e => setFilters({...filters, project_id: e.target.value})} style={{ minWidth: 0, flex: 1 }}>
          <option value="">همه پروژه‌ها</option>
          {projects.map(p => <option key={p.id} value={p.id}>{p.title}</option>)}
        </select>
        <select className="form-select" value={filters.assignee_id} onChange={e => setFilters({...filters, assignee_id: e.target.value})} style={{ minWidth: 0, flex: 1 }}>
          <option value="">همه اعضا</option>
          {users.map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
        </select>
        <select className="form-select" value={filters.priority} onChange={e => setFilters({...filters, priority: e.target.value})} style={{ minWidth: 0, flex: 1 }}>
          <option value="">همه اولویت‌ها</option>
          <option value="low">کم</option>
          <option value="medium">متوسط</option>
          <option value="high">زیاد</option>
          <option value="urgent">فوری</option>
        </select>
      </div>

      {loading ? <div className="skeleton" style={{ height: 400 }} /> : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '0.75rem', minHeight: '60vh', alignItems: 'start' }}>
          {columns.map(col => (
            <div key={col.key} style={{ background: 'var(--gray-50)', borderRadius: 'var(--radius)', padding: '0.75rem', minWidth: 0 }}
              onDragOver={e => e.preventDefault()}
              onDrop={() => handleDrop(col.key)}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.75rem' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '0.375rem', minWidth: 0 }}>
                  <div style={{ width: 10, height: 10, borderRadius: '50%', background: col.color, flexShrink: 0 }} />
                  <h3 style={{ fontSize: '0.8125rem', fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{col.label}</h3>
                  <span style={{ fontSize: '0.75rem', color: 'var(--gray-400)', background: 'var(--gray-200)', padding: '0.125rem 0.375rem', borderRadius: 9999, flexShrink: 0 }}>{(board[col.key] || []).length}</span>
                </div>
                <button className="btn btn-sm btn-secondary" onClick={() => setNewTask({ column: col.key, title: '' })} style={{ padding: '0.125rem 0.5rem', fontSize: '0.8125rem', flexShrink: 0 }}>+</button>
              </div>

              {newTask.column === col.key && (
                <div style={{ marginBottom: '0.5rem' }}>
                  <input className="form-input" autoFocus value={newTask.title} onChange={e => setNewTask({...newTask, title: e.target.value})}
                    onKeyDown={e => { if (e.key === 'Enter') handleAddTask(col.key); if (e.key === 'Escape') setNewTask({ column: '', title: '' }); }}
                    placeholder="عنوان..." style={{ fontSize: '0.8125rem', marginBottom: '0.375rem', padding: '0.375rem 0.5rem' }} />
                  <div style={{ display: 'flex', gap: '0.375rem' }}>
                    <button className="btn btn-primary btn-sm" onClick={() => handleAddTask(col.key)} style={{ padding: '0.25rem 0.5rem', fontSize: '0.75rem' }}>ذخیره</button>
                    <button className="btn btn-secondary btn-sm" onClick={() => setNewTask({ column: '', title: '' })} style={{ padding: '0.25rem 0.5rem', fontSize: '0.75rem' }}>لغو</button>
                  </div>
                </div>
              )}

              <div style={{ display: 'flex', flexDirection: 'column', gap: '0.625rem' }}>
                {(board[col.key] || []).map(task => (
                  <div key={task.id} draggable onDragStart={() => handleDragStart(task, col.key)} onClick={() => openTaskDetail(task)}
                    style={{ background: 'var(--surface)', borderRadius: 'var(--radius-sm)', padding: '0.625rem', boxShadow: '0 1px 2px rgba(0,0,0,0.05)', cursor: 'grab', border: '1px solid var(--gray-100)', wordBreak: 'break-word' }}
                  >
                    <div style={{ display: 'flex', justifyContent: 'space-between', gap: '0.25rem', marginBottom: '0.375rem' }}>
                      <span style={{ fontSize: '0.8125rem', fontWeight: 500, lineHeight: 1.3 }}>{task.title}</span>
                      <div style={{ flexShrink: 0 }}><PriorityBadge priority={task.priority} /></div>
                    </div>
                    <div style={{ display: 'grid', gap: '0.375rem' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '0.375rem', minWidth: 0 }}>
                        <div className="avatar avatar-sm" style={{ width: 20, height: 20, fontSize: '0.625rem', flexShrink: 0 }}>{task.assignee?.name?.[0] || '?'}</div>
                        <span style={{ fontSize: '0.6875rem', color: 'var(--gray-500)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{task.assignee?.name || 'بدون مسئول'}</span>
                      </div>
                      <div style={{ display: 'flex', justifyContent: 'space-between', gap: '0.5rem', color: 'var(--gray-500)', fontSize: '0.6875rem' }}>
                        <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{task.project?.title || 'بدون پروژه'}</span>
                        <span style={{ whiteSpace: 'nowrap', color: isPastDate(task.due_date) && task.status !== 'done' ? 'var(--danger)' : 'var(--gray-500)' }}>
                          {task.due_date ? formatJalaliDate(task.due_date) : 'بدون ددلاین'}
                        </span>
                      </div>
                      <div style={{ display: 'flex', justifyContent: 'space-between', gap: '0.375rem', fontSize: '0.6875rem', color: 'var(--gray-400)' }}>
                        <span>{task.estimated_time ? `${task.estimated_time} ساعت` : 'بدون تخمین'}</span>
                        <span>{task.blocker_type ? 'دارای بلاکر · ' : ''}{task.comments_count ?? 0} نظر · {task.files_count ?? 0} فایل</span>
                      </div>
                    </div>
                  </div>
                ))}
                {(board[col.key] || []).length === 0 && !newTask.column && (
                  <div style={{ textAlign: 'center', padding: '1rem', color: 'var(--gray-400)', fontSize: '0.875rem' }}>
                    تسکی وجود ندارد
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      )}

      {selectedTask && (
        <Modal
          title="جزئیات تسک"
          onClose={() => setSelectedTask(null)}
          size="xl"
          footer={(
            <div className="modal-step-footer">
              <button type="button" className="btn btn-secondary" disabled={detailStep === 0} onClick={() => setDetailStep((step) => Math.max(0, step - 1))}>مرحله قبل</button>
              <span>مرحله {detailStep + 1} از ۳</span>
              <button type="button" className="btn btn-primary" disabled={detailStep === 2} onClick={() => setDetailStep((step) => Math.min(2, step + 1))}>مرحله بعد</button>
            </div>
          )}
        >
          {detailLoading ? <div className="skeleton" style={{ height: 280, borderRadius: 'var(--radius)' }} /> : (
            <div className="task-detail-modal">
              <div className="modal-wizard-steps" role="tablist" aria-label="بخش‌های جزئیات تسک">
                <button type="button" role="tab" aria-selected={detailStep === 0} className={detailStep === 0 ? 'active' : detailStep > 0 ? 'complete' : ''} onClick={() => setDetailStep(0)}><span>۱</span>نمای کلی</button>
                <button type="button" role="tab" aria-selected={detailStep === 1} className={detailStep === 1 ? 'active' : detailStep > 1 ? 'complete' : ''} onClick={() => setDetailStep(1)}><span>۲</span>بلاکر</button>
                <button type="button" role="tab" aria-selected={detailStep === 2} className={detailStep === 2 ? 'active' : ''} onClick={() => setDetailStep(2)}><span>۳</span>یادداشت‌ها</button>
              </div>

              {detailStep === 0 && (
                <div className="task-detail-wizard-panel">
                  <div className="task-detail-head">
                    <div>
                      <h2>{selectedTask.title}</h2>
                      <p>{selectedTask.description || 'توضیحی برای این تسک ثبت نشده است.'}</p>
                    </div>
                    <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap' }}>
                      <StatusBadge status={selectedTask.status} />
                      <PriorityBadge priority={selectedTask.priority} />
                    </div>
                  </div>
                  <div className="task-detail-grid compact">
                    <Info label="پروژه" value={selectedTask.project?.title || 'بدون پروژه'} />
                    <Info label="مسئول" value={selectedTask.assignee?.name || 'بدون مسئول'} />
                    <Info label="گزارش‌دهنده" value={selectedTask.reporter?.name || '—'} />
                    <Info label="شروع" value={selectedTask.start_date ? formatJalaliDate(selectedTask.start_date) : '—'} />
                    <Info label="ددلاین" value={selectedTask.due_date ? formatJalaliDate(selectedTask.due_date) : 'بدون ددلاین'} />
                    <Info label="تخمین" value={selectedTask.estimated_time ? `${selectedTask.estimated_time} ساعت` : '—'} />
                  </div>
                </div>
              )}

              {detailStep === 1 && (
                <div className="card task-detail-section task-detail-wizard-panel">
                  <h3>بلاکر</h3>
                  <div className="form-group">
                    <label className="form-label">نوع بلاکر</label>
                    <FormSelect value={blockerForm.blocker_type} onChange={(e) => setBlockerForm({ ...blockerForm, blocker_type: e.target.value })}>
                      {blockerOptions.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
                    </FormSelect>
                  </div>
                  <div className="form-group">
                    <label className="form-label">توضیح بلاکر</label>
                    <input className="form-input" value={blockerForm.blocker_note} onChange={(e) => setBlockerForm({ ...blockerForm, blocker_note: e.target.value })} placeholder="مثلاً منتظر پاسخ تیم بک‌اند" />
                  </div>
                  <button className="btn btn-primary btn-sm" onClick={saveBlocker} disabled={savingDetail}><Save size={14} /> ذخیره بلاکر</button>
                </div>
              )}

              {detailStep === 2 && (
                <div className="task-notes-wizard task-detail-wizard-panel">
                <div className="card task-detail-section">
                  <h3>نوت و منشن</h3>
                  <form onSubmit={addNote}>
                  <div className="form-group">
                    <label className="form-label">نوت</label>
                    <textarea className="form-textarea task-note-input" value={noteForm.body} onChange={(e) => setNoteForm({ ...noteForm, body: e.target.value })} placeholder="یادداشت خود را بنویسید..." />
                  </div>
                  <div className="form-group">
                    <label className="form-label">منشن برای پیگیری</label>
                    <FormSelect value={noteForm.mentioned_user_id} onChange={(e) => setNoteForm({ ...noteForm, mentioned_user_id: e.target.value })}>
                      <option value="">بدون منشن</option>
                      {users.map((user) => <option key={user.id} value={user.id}>{user.name}</option>)}
                    </FormSelect>
                  </div>
                  <button className="btn btn-primary" disabled={savingDetail || !noteForm.body.trim()}><MessageSquare size={16} /> ثبت نوت</button>
                  </form>
                </div>
                  <div className="task-notes">
                    <h3>نوت‌های اخیر</h3>
                    {comments.length === 0 ? <div style={{ color: 'var(--gray-400)', fontSize: '0.875rem' }}>هنوز نوتی ثبت نشده است.</div> : (
                      <>
                        {comments.slice(commentIndex, commentIndex + 1).map((comment) => (
                          <div className="task-note" key={comment.id}>
                            <div className="avatar avatar-sm">{comment.user?.name?.[0] || '?'}</div>
                            <div>
                              <strong>{comment.user?.name || 'کاربر'}</strong>
                              <p>{comment.body}</p>
                              <span>{comment.created_at ? formatJalaliDate(comment.created_at) : ''}</span>
                            </div>
                          </div>
                        ))}
                        <div className="schedule-wizard-navigation">
                          <button type="button" className="btn btn-secondary btn-sm" disabled={commentIndex === 0} onClick={() => setCommentIndex((index) => Math.max(0, index - 1))}>قبلی</button>
                          <span>{commentIndex + 1} از {comments.length}</span>
                          <button type="button" className="btn btn-secondary btn-sm" disabled={commentIndex >= comments.length - 1} onClick={() => setCommentIndex((index) => Math.min(comments.length - 1, index + 1))}>بعدی</button>
                        </div>
                      </>
                    )}
                  </div>
                </div>
              )}
            </div>
          )}
        </Modal>
      )}
    </div>
  );
}

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