'use client';

import { useState, useMemo } from 'react';
import { X } from 'lucide-react';
import { useBugStore } from '@/stores/useBugStore';
import { useTestCaseStore } from '@/stores/useTestCaseStore';
import { useDevTaskStore } from '@/stores/useDevTaskStore';
import { useRequirementStore } from '@/stores/useRequirementStore';
import { useMemberStore } from '@/stores/useMemberStore';
import { useAuthStore } from '@/stores/useAuthStore';
import type { Priority } from '@/lib/derive';
import type { BugSeverity } from '@/lib/bug';

interface Props {
  testCaseId: string;
  onClose: () => void;
}

export function BugCreateModal({ testCaseId, onClose }: Props) {
  const { createBug } = useBugStore();
  const { testCases } = useTestCaseStore();
  const { tasks: devTasks } = useDevTaskStore();
  const { requirements } = useRequirementStore();
  const { members } = useMemberStore();
  const user = useAuthStore((s) => s.user);

  const tc = testCases.find((c) => c.id === testCaseId);
  const requirement = requirements.find((r) => r.id === tc?.requirementId);

  // 推导默认负责人
  const defaultAssignee = useMemo(() => {
    if (!tc) return '';
    const reqTasks = devTasks.filter((t) => t.requirementId === tc.requirementId);
    const inProgress = reqTasks.filter((t) => t.status === 'in_progress').sort((a, b) => b.createdAt.localeCompare(a.createdAt));
    if (inProgress.length > 0) return inProgress[0].assigneeId;
    const latest = reqTasks.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
    return latest.length > 0 ? latest[0].assigneeId : '';
  }, [tc, devTasks]);

  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [severity, setSeverity] = useState<BugSeverity>('major');
  const [priority, setPriority] = useState<Priority>(tc?.priority || 'P1');
  const [assigneeId, setAssigneeId] = useState(defaultAssignee);

  const canSubmit = title.trim() && description.trim() && assigneeId;

  const handleSubmit = () => {
    if (!canSubmit) return;
    createBug({
      testCaseId,
      title: title.trim(),
      description: description.trim(),
      severity,
      priority,
      reportedBy: user?.name || '系统',
      assigneeId,
    });
    onClose();
  };

  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/40" onClick={onClose}>
      <div className="w-full max-w-md rounded-2xl bg-[var(--bg-card)] border border-[var(--line)] p-6 shadow-[var(--shadow-md)]" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-[14px] font-semibold text-[var(--ink)]">提交 Bug</h3>
          <button onClick={onClose} className="rounded-md p-1 hover:bg-[var(--bg-subtle)]"><X className="h-4 w-4 text-[var(--ink-muted)]" /></button>
        </div>

        {/* 只读关联信息 */}
        <div className="rounded-lg bg-[var(--bg-subtle)] px-3 py-2 mb-4 space-y-1 text-[12px]">
          <div><span className="text-[var(--ink-muted)]">关联用例：</span><span className="text-[var(--ink)]">{tc?.caseNo} {tc?.title}</span></div>
          {requirement && <div><span className="text-[var(--ink-muted)]">关联需求：</span><span className="text-[var(--ink)]">{requirement.code} {requirement.title}</span></div>}
        </div>

        <div className="space-y-3">
          <div>
            <label className="block text-[12px] text-[var(--ink-soft)] mb-1">Bug 标题 *</label>
            <input value={title} onChange={(e) => setTitle(e.target.value)} className="h-9 w-full rounded-lg border border-[var(--line)] bg-[var(--bg)] px-3 text-[13px] focus:border-[var(--accent)] focus:outline-none" placeholder="简要描述问题" />
          </div>
          <div>
            <label className="block text-[12px] text-[var(--ink-soft)] mb-1">Bug 描述 *</label>
            <textarea rows={3} value={description} onChange={(e) => setDescription(e.target.value)} className="w-full rounded-lg border border-[var(--line)] bg-[var(--bg)] px-3 py-2 text-[13px] focus:border-[var(--accent)] focus:outline-none resize-none" placeholder="复现步骤、实际结果、预期结果" />
          </div>
          <div className="grid grid-cols-3 gap-3">
            <div>
              <label className="block text-[12px] text-[var(--ink-soft)] mb-1">严重程度</label>
              <select value={severity} onChange={(e) => setSeverity(e.target.value as BugSeverity)} className="h-9 w-full rounded-lg border border-[var(--line)] bg-[var(--bg)] px-3 text-[13px] focus:border-[var(--accent)] focus:outline-none">
                <option value="critical">致命</option>
                <option value="major">严重</option>
                <option value="minor">一般</option>
                <option value="trivial">轻微</option>
              </select>
            </div>
            <div>
              <label className="block text-[12px] text-[var(--ink-soft)] mb-1">优先级</label>
              <select value={priority} onChange={(e) => setPriority(e.target.value as Priority)} className="h-9 w-full rounded-lg border border-[var(--line)] bg-[var(--bg)] px-3 text-[13px] focus:border-[var(--accent)] focus:outline-none">
                {(['P0','P1','P2','P3'] as Priority[]).map((p) => <option key={p} value={p}>{p}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-[12px] text-[var(--ink-soft)] mb-1">修复人 *</label>
              <select value={assigneeId} onChange={(e) => setAssigneeId(e.target.value)} className="h-9 w-full rounded-lg border border-[var(--line)] bg-[var(--bg)] px-3 text-[13px] focus:border-[var(--accent)] focus:outline-none">
                <option value="">选择修复人</option>
                {members.map((m) => <option key={m.id} value={m.name}>{m.name}</option>)}
              </select>
            </div>
          </div>
        </div>
        <div className="flex justify-end gap-2 pt-4 border-t border-[var(--line)] mt-4">
          <button onClick={onClose} className="h-8 px-3 rounded-lg text-[12px] font-medium border border-[var(--line)] text-[var(--ink-soft)] hover:bg-[var(--bg-subtle)]">取消</button>
          <button onClick={handleSubmit} disabled={!canSubmit} className="h-8 px-4 rounded-lg text-[12px] font-medium bg-red-500 text-white hover:bg-red-600 disabled:opacity-50">提交 Bug</button>
        </div>
      </div>
    </div>
  );
}
