'use client';

import { useState } from 'react';
import { Plus, Trash2 } from 'lucide-react';
import { useTaskWorklogStore } from '@/stores/useTaskWorklogStore';
import { useAuthStore } from '@/stores/useAuthStore';
import { getTaskWorklogs } from '@/lib/task-worklog';
import { formatLocalDate } from '@/lib/format';

interface Props {
  taskId: string;
}

export function WorklogPanel({ taskId }: Props) {
  const { worklogs, addWorklog, deleteWorklog } = useTaskWorklogStore();
  const user = useAuthStore((s) => s.user);

  const taskLogs = getTaskWorklogs(worklogs, taskId);
  const totalHours = taskLogs.reduce((sum, w) => sum + w.hours, 0);

  const today = formatLocalDate();
  const [date, setDate] = useState(today);
  const [hours, setHours] = useState<number>(1);
  const [workContent, setWorkContent] = useState('');
  const [adding, setAdding] = useState(false);

  const handleAdd = () => {
    if (!workContent.trim() || hours <= 0) return;
    addWorklog({ taskId, userId: user?.name || '', date, hours, workContent: workContent.trim() });
    setWorkContent('');
    setHours(1);
    setAdding(false);
  };

  const handleDelete = (id: string) => {
    deleteWorklog(id);
  };

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <span className="text-[12px] font-medium text-[var(--ink)]">工时记录（累计 {totalHours}h）</span>
        {!adding && (
          <button onClick={() => setAdding(true)} className="flex items-center gap-1 text-[11px] text-[var(--accent)] hover:underline">
            <Plus className="h-3 w-3" />登记工时
          </button>
        )}
      </div>

      {adding && (
        <div className="rounded-lg border border-[var(--line)] bg-[var(--bg)] p-3 space-y-2">
          <div className="grid grid-cols-2 gap-2">
            <input type="date" value={date} onChange={(e) => setDate(e.target.value)} className="h-8 rounded-md border border-[var(--line)] px-2 text-[12px] focus:border-[var(--accent)] focus:outline-none" />
            <input type="number" min={0.5} step={0.5} value={hours} onChange={(e) => setHours(parseFloat(e.target.value) || 0)} placeholder="小时" className="h-8 rounded-md border border-[var(--line)] px-2 text-[12px] focus:border-[var(--accent)] focus:outline-none" />
          </div>
          <input value={workContent} onChange={(e) => setWorkContent(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') handleAdd(); }} placeholder="工作内容（必填）" className="h-8 w-full rounded-md border border-[var(--line)] px-2 text-[12px] focus:border-[var(--accent)] focus:outline-none" />
          <div className="flex justify-end gap-2">
            <button onClick={() => setAdding(false)} className="h-7 px-2 text-[11px] text-[var(--ink-muted)] hover:text-[var(--ink)]">取消</button>
            <button onClick={handleAdd} disabled={!workContent.trim() || hours <= 0} className="h-7 px-3 rounded-md text-[11px] font-medium bg-[var(--accent)] text-white disabled:opacity-50">确认</button>
          </div>
        </div>
      )}

      {taskLogs.length === 0 && !adding && (
        <p className="text-[12px] text-[var(--ink-muted)] py-2">暂无工时记录</p>
      )}

      {taskLogs.map((log) => (
        <div key={log.id} className="flex items-start gap-2 py-1.5 border-b border-[var(--line)] last:border-0">
          <div className="flex-1">
            <p className="text-[12px] text-[var(--ink)]">{log.workContent}</p>
            <p className="text-[10px] text-[var(--ink-muted)]">{log.date} · {log.hours}h · {log.userId}</p>
          </div>
          <button onClick={() => handleDelete(log.id)} className="p-1 rounded hover:bg-red-50">
            <Trash2 className="h-3 w-3 text-[var(--ink-muted)] hover:text-red-500" />
          </button>
        </div>
      ))}
    </div>
  );
}
