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 PwaSprintTaskCard({ task, permissions, onStatus, onComment, onDone }) {
  const navigate = useNavigate();
  const { open, dragging, translateX, revealRatio, close, swipeHandlers } = useHorizontalSwipeMenu({ railWidth: 176, threshold: 72 });
  const isDone = task.status === 'done';
  const isOverdue = task.due_date && new Date(task.due_date) < new Date(new Date().toDateString()) && !['done', 'canceled', 'cancelled'].includes(task.status);

  const openTask = () => {
    close();
    navigate(`/pwa/tasks/${task.id}`);
  };

  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={() => { close(); onStatus?.(task); }} disabled={!permissions.canEdit}><RotateCcw size={16} /><span>وضعیت</span></button>
        <button type="button" onClick={() => { close(); onComment?.(task); }} disabled={!permissions.canComment}><MessageCircle size={16} /><span>کامنت</span></button>
        <button type="button" onClick={() => { close(); onDone?.(task); }} disabled={!permissions.canEdit || isDone}><CheckCircle2 size={16} /><span>انجام شد</span></button>
      </div>

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