import { AlertCircle, Plus, RefreshCcw } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import api from '../services/api';
import { useAuth } from '../context/AuthContext';
import PwaBottomSheet from './PwaBottomSheet';
import PwaCreateTaskSheet from './PwaCreateTaskSheet';
import PwaSprintBoard from './PwaSprintBoard';
import PwaSprintEmptyState from './PwaSprintEmptyState';
import PwaSprintFilters from './PwaSprintFilters';
import PwaSprintSelector from './PwaSprintSelector';
import PwaSprintStatusSheet from './PwaSprintStatusSheet';
import PwaSprintSummaryCard from './PwaSprintSummaryCard';
import { usePwaNotification } from './PwaNotificationProvider';

export default function PwaSprintPage() {
  const { user } = useAuth();
  const { notify } = usePwaNotification();
  const [sprints, setSprints] = useState([]);
  const [selectedId, setSelectedId] = useState('');
  const [filter, setFilter] = useState('all');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [statusTask, setStatusTask] = useState(null);
  const [commentTask, setCommentTask] = useState(null);
  const [comment, setComment] = useState('');
  const [commentError, setCommentError] = useState('');
  const [savingStatus, setSavingStatus] = useState(false);
  const [savingComment, setSavingComment] = useState(false);
  const [createOpen, setCreateOpen] = useState(false);

  const fetchSprints = async (silent = false) => {
    if (!silent) setLoading(true);
    setError('');
    try {
      const { data } = await api.get('/pwa/sprints');
      const next = data.data || [];
      setSprints(next);
      setSelectedId((current) => current && next.some((item) => String(item.id) === String(current))
        ? current
        : String(next.find((item) => item.status === 'active')?.id || next[0]?.id || ''));
    } catch (err) {
      setError(err.response?.data?.message || 'خطا در دریافت اطلاعات اسپرینت. دوباره تلاش کنید.');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { fetchSprints(); }, []);

  const sprint = sprints.find((item) => String(item.id) === String(selectedId)) || sprints[0];
  const permissions = {
    canEdit: Boolean(sprint?.capabilities?.can_update_task_status),
    canComment: Boolean(sprint?.capabilities?.can_comment),
    canCreate: Boolean(sprint?.capabilities?.can_create_task),
  };

  const filteredTasks = useMemo(() => {
    const tasks = sprint?.tasks || [];
    const today = new Date().toISOString().slice(0, 10);
    return tasks.filter((task) => {
      const overdue = task.due_date && task.due_date < today && !['done', 'canceled', 'cancelled'].includes(task.status);
      if (filter === 'mine') return String(task.assignee?.id) === String(user?.id);
      if (filter === 'overdue') return overdue;
      if (filter === 'today') return task.due_date === today;
      if (filter === 'urgent') return task.priority === 'urgent';
      if (filter === 'done') return task.status === 'done';
      return true;
    });
  }, [filter, sprint, user?.id]);

  const replaceTask = (updatedTask) => {
    setSprints((current) => current.map((item) => item.id !== sprint?.id ? item : ({
      ...item,
      tasks: (item.tasks || []).map((task) => task.id === updatedTask.id ? { ...task, ...updatedTask } : task),
    })));
  };

  const submitStatus = async (status) => {
    if (!statusTask) return;
    setSavingStatus(true);
    try {
      const { data } = await api.patch(`/pwa/tasks/${statusTask.id}/status`, { status });
      replaceTask(data.data);
      setStatusTask(null);
      notify({ tone: 'success', title: 'اسپرینت', message: 'وضعیت تسک تغییر کرد.' });
      fetchSprints(true);
    } catch (err) {
      notify({ tone: 'error', title: 'تغییر وضعیت', message: err.response?.data?.message || 'تغییر وضعیت انجام نشد.' });
    } finally {
      setSavingStatus(false);
    }
  };

  const submitComment = async (event) => {
    event.preventDefault();
    if (!comment.trim()) {
      setCommentError('متن کامنت الزامی است.');
      return;
    }

    setSavingComment(true);
    setCommentError('');
    try {
      await api.post(`/pwa/tasks/${commentTask.id}/comments`, { body: comment.trim() });
      setComment('');
      setCommentTask(null);
      notify({ tone: 'success', title: 'کامنت', message: 'کامنت ثبت شد.' });
      fetchSprints(true);
    } catch (err) {
      setCommentError(err.response?.data?.message || 'ثبت کامنت انجام نشد.');
    } finally {
      setSavingComment(false);
    }
  };

  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={() => fetchSprints()}><RefreshCcw size={16} /> تلاش دوباره</button>
      </section>
    );
  }
  if (!sprint) return <PwaSprintEmptyState message="اسپرینت فعالی برای نمایش وجود ندارد." />;

  return (
    <div className="pwa-sprint-page">
      {permissions.canCreate && (
        <section className="pwa-page-actions">
          <button type="button" onClick={() => setCreateOpen(true)}><Plus size={18} /> ایجاد تسک در اسپرینت</button>
        </section>
      )}

      <PwaSprintSelector sprints={sprints} selectedId={String(sprint.id)} onChange={setSelectedId} />
      <PwaSprintSummaryCard sprint={sprint} />
      <PwaSprintFilters value={filter} onChange={setFilter} />

      {filteredTasks.length ? (
        <PwaSprintBoard tasks={filteredTasks} permissions={permissions} onStatus={setStatusTask} onComment={setCommentTask} onDone={(task) => submitStatusForTask(task, 'done')} />
      ) : (
        <PwaSprintEmptyState message={filter === 'overdue' ? 'تسک عقب‌افتاده‌ای در این اسپرینت وجود ندارد.' : 'تسکی در این اسپرینت ثبت نشده است.'} />
      )}

      <PwaSprintStatusSheet task={statusTask} open={Boolean(statusTask)} saving={savingStatus} onClose={() => setStatusTask(null)} onSubmit={submitStatus} />

      <PwaBottomSheet
        open={Boolean(commentTask)}
        title="افزودن کامنت"
        onClose={() => { setCommentTask(null); setComment(''); setCommentError(''); }}
        footer={(
          <>
            <button type="button" className="pwa-sheet-cancel" onClick={() => setCommentTask(null)} disabled={savingComment}>انصراف</button>
            <button type="submit" form="pwa-sprint-comment-form" className="pwa-sheet-submit" disabled={savingComment}>
              {savingComment ? 'در حال ثبت...' : 'ثبت کامنت'}
            </button>
          </>
        )}
      >
        <form id="pwa-sprint-comment-form" onSubmit={submitComment} className="pwa-comment-form">
          <textarea value={comment} onChange={(event) => setComment(event.target.value)} placeholder="متن کامنت را بنویسید" rows={4} />
          {commentError && <small>{commentError}</small>}
        </form>
      </PwaBottomSheet>

      <PwaCreateTaskSheet
        open={createOpen}
        onClose={() => setCreateOpen(false)}
        initialProjectId={sprint.project?.id || ''}
        lockProject={Boolean(sprint.project?.id)}
        successMessage="تسک جدید ثبت شد. اتصال مستقیم به اسپرینت نیاز به پشتیبانی بک‌اند دارد."
        onCreated={() => fetchSprints(true)}
      />
    </div>
  );

  async function submitStatusForTask(task, status) {
    setStatusTask(task);
    setSavingStatus(true);
    try {
      const { data } = await api.patch(`/pwa/tasks/${task.id}/status`, { status });
      replaceTask(data.data);
      notify({ tone: 'success', title: 'اسپرینت', message: 'وضعیت تسک تغییر کرد.' });
      fetchSprints(true);
    } catch (err) {
      notify({ tone: 'error', title: 'تغییر وضعیت', message: err.response?.data?.message || 'تغییر وضعیت انجام نشد.' });
    } finally {
      setSavingStatus(false);
      setStatusTask(null);
    }
  }
}
