'use client';

import { useEffect, useState, useMemo } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { ChevronLeft, Pencil, Trash2 } from 'lucide-react';
import type { RequirementStatus } from '@/lib/requirement';
import { useProductStore } from '@/stores/useProductStore';
import { useRequirementStore } from '@/stores/useRequirementStore';
import { useOvertimeStore } from '@/stores/useOvertimeStore';
import { RequirementTable } from '@/components/product/RequirementTable';
import { RequirementForm } from '@/components/product/RequirementForm';
import { ProductForm } from '@/components/product/ProductForm';

const TABS = [
  { key: 'requirements' as const, label: '需求池' },
  { key: 'projects' as const, label: '项目' },
  { key: 'versions' as const, label: '版本' },
];

export default function ProductDetailPage() {
  const params = useParams();
  const router = useRouter();
  const productId = params.id as string;

  const { currentProduct, fetchProduct, updateProduct, deleteProduct } = useProductStore();
  const {
    requirements,
    fetchRequirements,
    deleteRequirement,
  } = useRequirementStore();
  const { records, fetchRecords } = useOvertimeStore();

  const [showReqForm, setShowReqForm] = useState(false);
  const [editingReq, setEditingReq] = useState<any>(null);
  const [editingProduct, setEditingProduct] = useState(false);
  const [activeTab, setActiveTab] = useState<'requirements' | 'projects' | 'versions'>('requirements');
  const [reqStatusFilter, setReqStatusFilter] = useState<RequirementStatus | null>(null);

  useEffect(() => {
    fetchProduct(productId);
    fetchRequirements();
    fetchRecords();
  }, [productId, fetchProduct, fetchRequirements, fetchRecords]);

  const productRequirements = useMemo(() => {
    let list = requirements.filter((r) => r.productId === productId);
    if (reqStatusFilter) list = list.filter((r) => r.status === reqStatusFilter);
    return list;
  }, [requirements, productId, reqStatusFilter]);

  const handleFilterChange = (status: RequirementStatus | null) => {
    setReqStatusFilter(status);
  };

  const handleCreateReq = async (data: { title: string; description: string; priority: number }) => {
    setShowReqForm(false);
  };

  const handleUpdateReq = async (data: { title: string; description: string; priority: number }) => {
    if (editingReq) {
      setEditingReq(null);
    }
  };

  const handleDeleteProduct = async () => {
    if (confirm('确定删除该产品？此操作不可撤销。')) {
      await deleteProduct(productId);
      router.push('/products');
    }
  };

  if (!currentProduct) {
    return (
      <div className="flex h-full items-center justify-center text-[13px] text-[var(--ink-muted)]">
        加载中…
      </div>
    );
  }

  return (
    <div className="flex h-full flex-col">
      <header className="flex h-14 shrink-0 items-center justify-between border-b border-[var(--line)] bg-[var(--bg-card)] px-6">
        <div className="flex items-center gap-2">
          <button
            onClick={() => router.push('/products')}
            className="flex h-7 items-center gap-1 rounded-md px-1.5 text-[12px] text-[var(--ink-muted)] hover:bg-[var(--bg-subtle)] hover:text-[var(--ink)]"
          >
            <ChevronLeft className="h-3.5 w-3.5" strokeWidth={2} />
            产品
          </button>
          <span className="text-[var(--ink-muted)]">/</span>
          <h1 className="text-[15px] font-semibold tracking-tight text-[var(--ink)]">
            {currentProduct.name}
          </h1>
        </div>
        <div className="flex gap-1.5">
          <button
            onClick={() => setEditingProduct(true)}
            className="flex h-8 items-center gap-1 rounded-lg border border-[var(--line)] bg-[var(--bg-card)] px-2.5 text-[12px] text-[var(--ink-soft)] hover:bg-[var(--bg-subtle)] hover:text-[var(--ink)]"
          >
            <Pencil className="h-3 w-3" strokeWidth={2} />
            编辑
          </button>
          <button
            onClick={handleDeleteProduct}
            className="flex h-8 items-center gap-1 rounded-lg border border-[var(--line)] bg-[var(--bg-card)] px-2.5 text-[12px] text-[var(--ink-soft)] hover:border-red-200 hover:bg-red-50 hover:text-red-600"
          >
            <Trash2 className="h-3 w-3" strokeWidth={2} />
            删除
          </button>
        </div>
      </header>

      <div className="border-b border-[var(--line)] bg-[var(--bg-card)] px-6">
        {currentProduct.description && (
          <p className="line-clamp-2 py-3 text-[13px] text-[var(--ink-soft)]">{currentProduct.description}</p>
        )}
        {/* 汇总统计 */}
        <div className="flex gap-4 py-3 border-b border-[var(--line-soft)]">
          {(() => {
            const allReqs = requirements.filter((r) => r.productId === productId);
            const adopted = allReqs.filter((r) => r.status === 'adopted' || r.status === 'planned').length;
            const developing = allReqs.filter((r) => r.status === 'developing' || r.status === 'testing').length;
            const released = allReqs.filter((r) => r.status === 'released').length;
            const projectReqs = allReqs.filter((r) => r.projectId);
            const projectIds = [...new Set(projectReqs.map((r) => r.projectId!))];
            const overtimeHours = Math.round(records.filter((r) => projectIds.includes(r.projectId)).reduce((sum, r) => sum + r.duration, 0) * 10) / 10;
            return (
              <>
                <div className="text-center"><div className="text-[16px] font-semibold text-[var(--ink)]">{allReqs.length}</div><div className="text-[11px] text-[var(--ink-muted)]">需求总数</div></div>
                <div className="text-center"><div className="text-[16px] font-semibold text-blue-600">{adopted}</div><div className="text-[11px] text-[var(--ink-muted)]">已采纳</div></div>
                <div className="text-center"><div className="text-[16px] font-semibold text-amber-600">{developing}</div><div className="text-[11px] text-[var(--ink-muted)]">开发中</div></div>
                <div className="text-center"><div className="text-[16px] font-semibold text-green-600">{released}</div><div className="text-[11px] text-[var(--ink-muted)]">已发布</div></div>
                <div className="text-center"><div className="text-[16px] font-semibold text-red-500">{overtimeHours}h</div><div className="text-[11px] text-[var(--ink-muted)]">加班时长</div></div>
              </>
            );
          })()}
        </div>
        <div className="flex gap-1">
          {TABS.map((tab) => (
            <button
              key={tab.key}
              onClick={() => setActiveTab(tab.key)}
              className={`relative h-9 px-3 text-[13px] transition-colors ${
                activeTab === tab.key
                  ? 'font-medium text-[var(--ink)]'
                  : 'text-[var(--ink-soft)] hover:text-[var(--ink)]'
              }`}
            >
              {tab.label}
              {activeTab === tab.key && (
                <span className="absolute bottom-0 left-2 right-2 h-0.5 rounded-full bg-[var(--accent)]" />
              )}
            </button>
          ))}
        </div>
      </div>

      <div className="flex-1 overflow-y-auto">
        <div className="p-5">
          {editingProduct && (
            <div className="mb-5 rounded-2xl border border-[var(--line)] bg-[var(--bg-card)] p-6 shadow-[var(--shadow-sm)]">
              <h3 className="mb-4 text-[13px] font-semibold text-[var(--ink)]">编辑产品</h3>
              <ProductForm
                initialData={{ name: currentProduct.name, description: currentProduct.description }}
                onSubmit={async (data) => {
                  await updateProduct(productId, data);
                  setEditingProduct(false);
                  await fetchProduct(productId);
                }}
                onCancel={() => setEditingProduct(false)}
              />
            </div>
          )}

          {activeTab === 'requirements' && (
            <>
              {(showReqForm || editingReq) && (
                <div className="mb-5 rounded-2xl border border-[var(--line)] bg-[var(--bg-card)] p-6 shadow-[var(--shadow-sm)]">
                  <h3 className="mb-4 text-[13px] font-semibold text-[var(--ink)]">
                    {editingReq ? '编辑需求' : '新建需求'}
                  </h3>
                  <RequirementForm
                    initialData={editingReq || undefined}
                    onSubmit={editingReq ? handleUpdateReq : handleCreateReq}
                    onCancel={() => {
                      setShowReqForm(false);
                      setEditingReq(null);
                    }}
                  />
                </div>
              )}
              <RequirementTable
                requirements={productRequirements as any}
                statusFilter={reqStatusFilter}
                onFilterChange={handleFilterChange}
                onEdit={(req) => setEditingReq(req)}
                onStatusChange={() => {}}
                onDelete={(id) => deleteRequirement(id)}
                onCreate={() => setShowReqForm(true)}
              />
            </>
          )}

          {activeTab === 'projects' && (
            <div className="rounded-2xl border border-dashed border-[var(--line)] bg-[var(--bg-card)] py-20 text-center text-[13px] text-[var(--ink-muted)]">
              项目管理功能开发中
            </div>
          )}

          {activeTab === 'versions' && (
            <div className="rounded-2xl border border-dashed border-[var(--line)] bg-[var(--bg-card)] py-20 text-center text-[13px] text-[var(--ink-muted)]">
              版本管理功能开发中
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
