import { AlertCircle, ClipboardList, Plus, Search } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useSearchParams } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import api from '../services/api';
import PwaBottomSheet from './PwaBottomSheet';
import PwaCreateTaskSheet from './PwaCreateTaskSheet';
import PwaTaskCard from './PwaTaskCard';
import { usePwaNotification } from './PwaNotificationProvider';
import { hasPermission, pwaTaskStatusOptions } from './pwaTaskMeta';

const filters = [
  { key: 'all', label: 'همه', empty: 'تسکی برای نمایش وجود ندارد.' },
  { key: 'today', label: 'امروز', empty: 'برای امروز تسکی نداری.' },
  { key: 'overdue', label: 'عقب‌افتاده', empty: 'تسک عقب‌افتاده‌ای وجود ندارد.' },
  { key: 'active', label: 'در حال انجام', empty: 'تسک فعالی برای نمایش وجود ندارد.' },
  { key: 'done', label: 'انجام‌شده', empty: 'تسک انجام‌شده‌ای برای نمایش وجود ندارد.' },
  { key: 'urgent', label: 'فوری', empty: 'تسک فوری برای نمایش وجود ندارد.' },
];

export default function PwaTasks() {
  const { user } = useAuth();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const { notify } = usePwaNotification();
  const [items, setItems] = useState([]);
  const [filter, setFilter] = useState('all');
  const [search, setSearch] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [statusTask, setStatusTask] = useState(null);
  const [commentTask, setCommentTask] = useState(null);
  const [createOpen, setCreateOpen] = useState(false);
  const [comment, setComment] = useState('');
  const [commentError, setCommentError] = useState('');
  const [submittingComment, setSubmittingComment] = useState(false);

  const permissions = useMemo(() => ({
    canView: hasPermission(user, 'tasks.view'),
    canCreate: hasPermission(user, 'tasks.create'),
    canEdit: hasPermission(user, 'tasks.edit'),
    canComment: hasPermission(user, 'comments.create'),
  }), [user]);

  const activeFilter = filters.find((item) => item.key === filter) || filters[0];
  const projectId = searchParams.get('project_id');

  const fetchTasks = async (silent = false) => {
    if (!silent) setLoading(true);
    setError('');
    try {
      const { data } = await api.get('/pwa/tasks', { params: { filter, search: search.trim() || undefined, project_id: projectId || undefined, per_page: 30 } });
      setItems(data.data || []);
    } catch (err) {
      setError(err.response?.data?.message || 'خطا در دریافت تسک‌ها');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const timer = window.setTimeout(() => fetchTasks(), 260);
    return () => window.clearTimeout(timer);
  }, [filter, search, projectId]);

  useEffect(() => {
    const refresh = () => fetchTasks(true);
    window.addEventListener('pwa:task-created', refresh);
    return () => window.removeEventListener('pwa:task-created', refresh);
  }, [filter, search, projectId]);

  const updateTaskInList = (task) => {
    setItems((current) => current.map((item) => item.id === task.id ? { ...item, ...task } : item));
  };

  const changeStatus = async (task, status) => {
    try {
      const { data } = await api.patch(`/pwa/tasks/${task.id}/status`, { status });
      updateTaskInList(data.data);
      setStatusTask(null);
      notify({ tone: 'success', title: 'تسک‌ها', message: 'وضعیت تسک تغییر کرد.' });
    } catch (err) {
      notify({ tone: 'error', title: 'تغییر وضعیت', message: err.response?.data?.message || 'تغییر وضعیت انجام نشد.' });
    }
  };

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

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

  if (!permissions.canView) {
    return (
      <section className="pwa-state-card error">
        <AlertCircle size={28} />
        <strong>شما مجوز مشاهده تسک‌ها را ندارید.</strong>
      </section>
    );
  }

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

      <label className="pwa-search-field">
        <Search size={18} />
        <input value={search} onChange={(event) => setSearch(event.target.value)} placeholder="جستجوی تسک یا پروژه" />
      </label>

      <div className="pwa-filter-row">
        {filters.map((item) => (
          <button key={item.key} type="button" className={filter === item.key ? 'active' : ''} onClick={() => setFilter(item.key)}>
            {item.label}
          </button>
        ))}
      </div>

      {loading ? (
        <div className="pwa-task-list">
          {[1, 2, 3].map((item) => <div className="pwa-skeleton task-card" key={item} />)}
        </div>
      ) : error ? (
        <section className="pwa-state-card error">
          <AlertCircle size={28} />
          <strong>{error}</strong>
          <button type="button" onClick={() => fetchTasks()}>تلاش دوباره</button>
        </section>
      ) : items.length ? (
        <div className="pwa-task-list">
          {items.map((task) => (
            <PwaTaskCard
              key={task.id}
              task={task}
              permissions={permissions}
              onOpen={(item) => navigate(`/pwa/tasks/${item.id}`)}
              onStatus={setStatusTask}
              onDone={(item) => changeStatus(item, 'done')}
              onComment={setCommentTask}
            />
          ))}
        </div>
      ) : (
        <section className="pwa-empty-card">
          <ClipboardList size={28} />
          <strong>{activeFilter.empty}</strong>
        </section>
      )}

      <PwaCreateTaskSheet open={createOpen} onClose={() => setCreateOpen(false)} />

      <PwaBottomSheet open={Boolean(statusTask)} title="تغییر وضعیت" onClose={() => setStatusTask(null)}>
        <div className="pwa-status-options">
          {pwaTaskStatusOptions.map((status) => (
            <button key={status.value} type="button" className={statusTask?.status === status.value ? 'active' : ''} onClick={() => changeStatus(statusTask, status.value)}>
              {status.label}
            </button>
          ))}
        </div>
      </PwaBottomSheet>

      <PwaBottomSheet
        open={Boolean(commentTask)}
        title="افزودن کامنت"
        onClose={() => { setCommentTask(null); setComment(''); setCommentError(''); }}
        footer={(
          <>
            <button type="button" className="pwa-sheet-cancel" onClick={() => setCommentTask(null)} disabled={submittingComment}>انصراف</button>
            <button type="submit" form="pwa-task-comment-form" className="pwa-sheet-submit" disabled={submittingComment}>
              {submittingComment ? 'در حال ثبت...' : 'ثبت کامنت'}
            </button>
          </>
        )}
      >
        <form id="pwa-task-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>
    </div>
  );
}
