import { CalendarDays, CheckCircle2, Eye, MessageCircle, RotateCcw, UserRound } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { formatJalaliDate } from '../utils/date';
import { pwaTaskPriorityLabels, pwaTaskStatusLabels } from './pwaTaskMeta';
import useHorizontalSwipeMenu from './useHorizontalSwipeMenu';

export default function PwaTaskCard({ task, permissions = {}, onOpen, onStatus, onComment, onDone }) {
  const navigate = useNavigate();
  const { open, dragging, translateX, revealRatio, close, swipeHandlers } = useHorizontalSwipeMenu({ railWidth: 176, threshold: 72 });
  const openTask = () => {
    close();
    if (onOpen) onOpen(task);
    else navigate(`/pwa/tasks/${task.id}`);
  };
  const changeStatus = () => {
    if (!permissions.canEdit) return;
    close();
    onStatus?.(task);
  };
  const addComment = () => {
    if (!permissions.canComment) return;
    close();
    onComment?.(task);
  };
  const markDone = () => {
    if (!permissions.canEdit || task.status === 'done') return;
    close();
    onDone?.(task);
  };

  return (
    <article className={`pwa-task-swipe ${open ? 'open' : ''} ${dragging ? 'dragging' : ''}`}>
      <div className="pwa-task-action-rail" style={{ '--task-rail-reveal': revealRatio }} aria-hidden={!open}>
        <button type="button" onClick={openTask}><Eye size={16} /><span>مشاهده</span></button>
        <button type="button" onClick={changeStatus} disabled={!permissions.canEdit}><RotateCcw size={16} /><span>وضعیت</span></button>
        <button type="button" onClick={addComment} disabled={!permissions.canComment}><MessageCircle size={16} /><span>کامنت</span></button>
        <button type="button" onClick={markDone} disabled={!permissions.canEdit || task.status === 'done'}><CheckCircle2 size={16} /><span>انجام شد</span></button>
      </div>

      <div
        className="pwa-task-card"
        style={{ '--task-card-translate-x': `${translateX}px`, '--task-rail-reveal': revealRatio }}
        {...swipeHandlers}
        onClick={() => {
          if (open) close();
          else openTask();
        }}
      >
        <div className="pwa-task-card-head">
          <h3>{task.title}</h3>
        </div>
        <p className="pwa-task-project">{task.project?.title || 'بدون پروژه'}</p>

        <div className="pwa-task-meta">
          <span className={`pwa-chip priority-${task.priority || 'medium'}`}>{pwaTaskPriorityLabels[task.priority] || 'معمولی'}</span>
          <span className="pwa-chip">{pwaTaskStatusLabels[task.status] || task.status || 'نامشخص'}</span>
        </div>
        <div className="pwa-task-info">
          <span><CalendarDays size={14} /> مهلت: {formatJalaliDate(task.due_date, 'بدون موعد')}</span>
          <span><UserRound size={14} /> مسئول: {task.assignee?.name || 'بدون مسئول'}</span>
        </div>
        {task.latest_comment && <p className="pwa-task-comment">آخرین کامنت: {task.latest_comment.body}</p>}
      </div>
    </article>
  );
}
