'use client';

import { useEffect, useMemo, useState } from 'react';
import { Search, Tag, Plus, X, ChevronDown } from 'lucide-react';
import { useProductStore } from '@/stores/useProductStore';
import { flattenVersions, flattenProjects } from '@/lib/derive';
import type { VersionWithContext } from '@/lib/derive';
import { VersionStatus, VERSION_STATUS_LABEL, VERSION_STATUS_DOT } from '@/lib/version-status';

const STATUS_TABS: { key: VersionStatus | 'all'; label: string }[] = [
  { key: 'all', label: '全部' },
  { key: 'developing', label: '开发中' },
  { key: 'planned', label: '规划中' },
  { key: 'released', label: '已发布' },
];

function parseVersionNumber(name: string): number[] {
  const match = name.match(/V([\d.]+)$/i);
  if (!match) return [0];
  return match[1].split('.').map(Number);
}

function compareVersionsDesc(a: string, b: string): number {
  const va = parseVersionNumber(a);
  const vb = parseVersionNumber(b);
  const len = Math.max(va.length, vb.length);
  for (let i = 0; i < len; i++) {
    const na = va[i] ?? 0;
    const nb = vb[i] ?? 0;
    if (nb !== na) return nb - na;
  }
  return 0;
}

function sortVersions(versions: VersionWithContext[]): VersionWithContext[] {
  return [...versions].sort((a, b) => {
    const projCmp = a.projectName.localeCompare(b.projectName, 'zh-CN');
    if (projCmp !== 0) return projCmp;
    return compareVersionsDesc(a.name, b.name);
  });
}

export default function VersionsPage() {
  const { overview, fetchOverview, createVersion } = useProductStore();
  const [search, setSearch] = useState('');
  const [statusTab, setStatusTab] = useState<VersionStatus | 'all'>('all');
  const [projectFilter, setProjectFilter] = useState('all');
  const [projectDropdownOpen, setProjectDropdownOpen] = useState(false);
  const [showModal, setShowModal] = useState(false);

  useEffect(() => { fetchOverview(); }, [fetchOverview]);

  const allVersions = useMemo(() => flattenVersions(overview), [overview]);
  const allProjects = useMemo(() => flattenProjects(overview), [overview]);

  const filtered = useMemo(() => {
    const list = allVersions.filter((v) => {
      if (statusTab !== 'all' && v.status !== statusTab) return false;
      if (projectFilter !== 'all' && v.projectName !== projectFilter) return false;
      if (search && !v.name.toLowerCase().includes(search.toLowerCase())) return false;
      return true;
    });
    return sortVersions(list);
  }, [allVersions, search, statusTab, projectFilter]);

  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-5">
        <div className="flex items-center gap-2.5">
          <h1 className="text-[15px] font-semibold tracking-tight text-[var(--ink)]">版本</h1>
          <span className="rounded-md bg-[var(--bg-subtle)] px-1.5 py-0.5 text-[11px] font-medium tabular-nums text-[var(--ink-soft)]">{allVersions.length}</span>
        </div>
        <button onClick={() => setShowModal(true)} className="flex h-8 items-center gap-1.5 rounded-lg bg-[var(--accent)] px-3 text-[13px] font-medium text-white shadow-[var(--shadow-sm)] hover:bg-[var(--accent-hover)] transition-colors">
          <Plus className="h-3.5 w-3.5" strokeWidth={2} />
          新建版本
        </button>
      </header>

      {/* Filters */}
      <div className="flex shrink-0 items-center gap-3 border-b border-[var(--line)] bg-[var(--bg-card)] px-5 py-3">
        <div className="relative">
          <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--ink-muted)]" strokeWidth={2} />
          <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="搜索版本号" className="h-8 w-64 rounded-lg border border-[var(--line)] bg-[var(--bg)] pl-8 pr-3 text-[13px] text-[var(--ink)] placeholder:text-[var(--ink-muted)] focus:border-[var(--accent)] focus:outline-none focus:ring-2 focus:ring-[var(--accent-ring)]" />
        </div>
        <div className="flex gap-1">
          {STATUS_TABS.map((tab) => (
            <button key={tab.key} onClick={() => setStatusTab(tab.key)} className={`h-8 rounded-lg px-3 text-[12.5px] transition-colors ${statusTab === tab.key ? 'bg-[var(--accent)] text-white' : 'border border-[var(--line)] bg-[var(--bg-card)] text-[var(--ink-soft)] hover:border-[var(--accent)] hover:text-[var(--accent)]'}`}>
              {tab.label}
            </button>
          ))}
        </div>
        <div className="relative">
          <button onClick={() => setProjectDropdownOpen(!projectDropdownOpen)} className="flex h-8 items-center gap-1.5 rounded-lg border border-[var(--line)] bg-[var(--bg-card)] px-3 text-[12.5px] text-[var(--ink-soft)] hover:border-[var(--accent)] hover:text-[var(--accent)] transition-colors">
            {projectFilter === 'all' ? '全部项目' : projectFilter}
            <ChevronDown className="h-3 w-3" strokeWidth={2} />
          </button>
          {projectDropdownOpen && (
            <div className="absolute left-0 top-full z-10 mt-1 min-w-[140px] rounded-lg border border-[var(--line)] bg-[var(--bg-card)] py-1 shadow-[var(--shadow-md)]">
              <button onClick={() => { setProjectFilter('all'); setProjectDropdownOpen(false); }} className={`block w-full px-3 py-1.5 text-left text-[12.5px] transition-colors ${projectFilter === 'all' ? 'bg-[var(--accent-soft)] text-[var(--accent)]' : 'text-[var(--ink-soft)] hover:bg-[var(--bg-hover)]'}`}>
                全部项目
              </button>
              {allProjects.map((p) => (
                <button key={p.id} onClick={() => { setProjectFilter(p.name); setProjectDropdownOpen(false); }} className={`block w-full px-3 py-1.5 text-left text-[12.5px] transition-colors ${projectFilter === p.name ? 'bg-[var(--accent-soft)] text-[var(--accent)]' : 'text-[var(--ink-soft)] hover:bg-[var(--bg-hover)]'}`}>
                  {p.name}
                </button>
              ))}
            </div>
          )}
        </div>
        <div className="ml-auto flex items-center gap-3 text-[11.5px] text-[var(--ink-muted)]">
          <span className="flex items-center gap-1.5"><span className="inline-block h-1.5 w-1.5 rounded-full bg-blue-500" />开发中</span>
          <span className="flex items-center gap-1.5"><span className="inline-block h-1.5 w-1.5 rounded-full bg-orange-500" />规划中</span>
          <span className="flex items-center gap-1.5"><span className="inline-block h-1.5 w-1.5 rounded-full bg-zinc-300" />已发布</span>
        </div>
      </div>

      {/* Content */}
      <div className="flex-1 overflow-y-auto bg-[var(--bg)]">
        <div className="px-5 py-4">
          {filtered.length === 0 ? (
            <div className="rounded-2xl border border-dashed border-[var(--line)] bg-[var(--bg-card)] py-20 text-center">
              <p className="text-[14px] font-medium text-[var(--ink-soft)]">没有找到匹配的版本</p>
              <p className="mt-1.5 text-[12.5px] text-[var(--ink-muted)]">尝试调整筛选条件</p>
            </div>
          ) : (
            <div className="overflow-hidden rounded-2xl border border-[var(--line)] bg-[var(--bg-card)] shadow-[var(--shadow-sm)]">
              <table className="w-full text-left text-[13px]">
                <thead>
                  <tr className="border-b border-[var(--line)] bg-[var(--bg-subtle)]">
                    <th className="px-4 py-2.5 text-[11.5px] font-medium uppercase tracking-wide text-[var(--ink-muted)]">版本号</th>
                    <th className="px-4 py-2.5 text-[11.5px] font-medium uppercase tracking-wide text-[var(--ink-muted)]">状态</th>
                    <th className="px-4 py-2.5 text-[11.5px] font-medium uppercase tracking-wide text-[var(--ink-muted)]">项目</th>
                    <th className="px-4 py-2.5 text-[11.5px] font-medium uppercase tracking-wide text-[var(--ink-muted)]">产品</th>
                    <th className="px-4 py-2.5 text-[11.5px] font-medium uppercase tracking-wide text-[var(--ink-muted)]">创建时间</th>
                  </tr>
                </thead>
                <tbody>
                  {filtered.map((v) => <VersionRow key={v.id} version={v} />)}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>

      {showModal && <NewVersionModal overview={overview} onClose={() => setShowModal(false)} onCreate={createVersion} />}
    </div>
  );
}

function VersionRow({ version }: { version: VersionWithContext }) {
  const dotCls = VERSION_STATUS_DOT[version.status];
  return (
    <tr className="border-b border-[var(--line-soft)] last:border-0 transition-colors hover:bg-[var(--bg-subtle)]">
      <td className="px-4 py-3 font-medium text-[var(--ink)]">
        <div className="flex items-center gap-2">
          <Tag className="h-3.5 w-3.5 text-[var(--ink-muted)]" strokeWidth={1.75} />
          {version.name}
        </div>
      </td>
      <td className="px-4 py-3">
        <span className="inline-flex items-center gap-1.5 text-[12px] text-[var(--ink-soft)]">
          <span className={`h-1.5 w-1.5 rounded-full ${dotCls}`} />
          {VERSION_STATUS_LABEL[version.status]}
        </span>
      </td>
      <td className="px-4 py-3 text-[var(--ink-soft)]">{version.projectName}</td>
      <td className="px-4 py-3 text-[var(--ink-muted)]">{version.productName}</td>
      <td className="px-4 py-3 text-[var(--ink-muted)] tabular-nums">{new Date(version.createdAt).toLocaleDateString('zh-CN')}</td>
    </tr>
  );
}

type IterationType = 'major' | 'minor' | 'patch';

interface NewVersionModalProps {
  overview: any[];
  onClose: () => void;
  onCreate: (productId: string, data: { name: string; status: VersionStatus }) => void;
}

function getNextVersion(existingVersions: any[], projectName: string, type: IterationType): string {
  const projectVersions = existingVersions
    .filter((v: any) => v.name.startsWith(projectName + 'V'))
    .map((v: any) => {
      const match = v.name.match(/V([\d.]+)$/i);
      return match ? match[1].split('.').map(Number) : null;
    })
    .filter(Boolean) as number[][];

  if (projectVersions.length === 0) {
    if (type === 'major') return '1.0';
    if (type === 'minor') return '0.1';
    return '0.0.1';
  }

  // Find the max version
  projectVersions.sort((a, b) => {
    const len = Math.max(a.length, b.length);
    for (let i = 0; i < len; i++) {
      const diff = (b[i] ?? 0) - (a[i] ?? 0);
      if (diff !== 0) return diff;
    }
    return 0;
  });
  const latest = projectVersions[0];

  if (type === 'major') {
    return `${(latest[0] ?? 0) + 1}.0`;
  } else if (type === 'minor') {
    return `${latest[0] ?? 0}.${(latest[1] ?? 0) + 1}`;
  } else {
    const major = latest[0] ?? 0;
    const minor = latest[1] ?? 0;
    const patch = latest[2] ?? 0;
    return `${major}.${minor}.${patch + 1}`;
  }
}

function NewVersionModal({ overview, onClose, onCreate }: NewVersionModalProps) {
  const [productId, setProductId] = useState('');
  const [projectId, setProjectId] = useState('');
  const [projectName, setProjectName] = useState('');
  const [iterationType, setIterationType] = useState<IterationType | ''>('');
  const [versionNumber, setVersionNumber] = useState('');
  const [status, setStatus] = useState<VersionStatus>('planned');
  const [submitting, setSubmitting] = useState(false);

  const selectedProduct = overview.find((p: any) => p.id === productId);
  const projects = selectedProduct?.projects ?? [];
  const existingVersions = selectedProduct?.versions ?? [];

  // When product changes, reset project
  const handleProductChange = (pid: string) => {
    setProductId(pid);
    setProjectId('');
    setProjectName('');
    setIterationType('');
    setVersionNumber('');
  };

  // When project changes
  const handleProjectChange = (projId: string) => {
    const proj = projects.find((p: any) => p.id === projId);
    setProjectId(projId);
    setProjectName(proj?.name ?? '');
    setIterationType('');
    setVersionNumber('');
  };

  // When iteration type changes, auto-generate version number
  const handleIterationChange = (type: IterationType) => {
    setIterationType(type);
    if (projectName) {
      const next = getNextVersion(existingVersions, projectName, type);
      setVersionNumber(next);
    }
  };

  const handleVersionInput = (val: string) => {
    // Only allow digits and dots
    const cleaned = val.replace(/[^\d.]/g, '');
    setVersionNumber(cleaned);
  };

  const canSubmit = productId && projectId && versionNumber && !submitting;

  const handleSubmit = async () => {
    if (!canSubmit) return;
    setSubmitting(true);
    try {
      await onCreate(productId, { name: `${projectName}V${versionNumber}`, status });
      onClose();
    } catch (e) {
      setSubmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40" onClick={onClose}>
      <div className="w-full max-w-md rounded-2xl bg-[var(--bg-card)] p-6 shadow-[var(--shadow-md)]" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between mb-5">
          <h2 className="text-[15px] font-semibold text-[var(--ink)]">新建版本</h2>
          <button onClick={onClose} className="rounded-lg p-1 text-[var(--ink-muted)] hover:bg-[var(--bg-hover)] transition-colors">
            <X className="h-4 w-4" strokeWidth={2} />
          </button>
        </div>

        <div className="space-y-4">
          {/* 产品选择 */}
          <div>
            <label className="mb-1.5 block text-[12.5px] font-medium text-[var(--ink-soft)]">产品选择<span className="text-red-500">*</span></label>
            <select value={productId} onChange={(e) => handleProductChange(e.target.value)} className="h-9 w-full rounded-lg border border-[var(--line)] bg-[var(--bg-card)] px-3 text-[13px] text-[var(--ink)] focus:border-[var(--accent)] focus:outline-none focus:ring-2 focus:ring-[var(--accent-ring)]">
              <option value="">请选择产品</option>
              {overview.map((p: any) => <option key={p.id} value={p.id}>{p.name}</option>)}
            </select>
          </div>

          {/* 项目选择 */}
          <div>
            <label className="mb-1.5 block text-[12.5px] font-medium text-[var(--ink-soft)]">项目选择<span className="text-red-500">*</span></label>
            <select value={projectId} onChange={(e) => handleProjectChange(e.target.value)} disabled={!productId} className="h-9 w-full rounded-lg border border-[var(--line)] bg-[var(--bg-card)] px-3 text-[13px] text-[var(--ink)] disabled:opacity-50 focus:border-[var(--accent)] focus:outline-none focus:ring-2 focus:ring-[var(--accent-ring)]">
              <option value="">请选择项目</option>
              {projects.map((p: any) => <option key={p.id} value={p.id}>{p.name}</option>)}
            </select>
          </div>

          {/* 迭代类型 */}
          <div>
            <label className="mb-1.5 block text-[12.5px] font-medium text-[var(--ink-soft)]">迭代类型<span className="text-red-500">*</span></label>
            <div className="grid grid-cols-3 gap-2">
              {([
                { key: 'major' as const, label: '大版本', hint: 'X.0' },
                { key: 'minor' as const, label: '中版本', hint: '1.X' },
                { key: 'patch' as const, label: '小版本', hint: '1.2.X' },
              ]).map((opt) => (
                <button key={opt.key} onClick={() => handleIterationChange(opt.key)} disabled={!projectId} className={`flex flex-col items-center gap-0.5 rounded-lg border px-3 py-2 transition-colors disabled:opacity-50 ${iterationType === opt.key ? 'border-[var(--accent)] bg-[var(--accent-soft)] text-[var(--accent)]' : 'border-[var(--line)] bg-[var(--bg-card)] text-[var(--ink-soft)] hover:border-[var(--accent)]'}`}>
                  <span className="text-[12.5px] font-medium">{opt.label}</span>
                  <span className="text-[10.5px] text-[var(--ink-muted)] tabular-nums">{opt.hint}</span>
                </button>
              ))}
            </div>
          </div>

          {/* 版本号 */}
          <div>
            <label className="mb-1.5 block text-[12.5px] font-medium text-[var(--ink-soft)]">版本号</label>
            <input value={versionNumber} onChange={(e) => handleVersionInput(e.target.value)} placeholder="1.0" className="h-9 w-full rounded-lg border border-[var(--line)] bg-[var(--bg-card)] px-3 text-[13px] tabular-nums text-[var(--ink)] placeholder:text-[var(--ink-muted)] focus:border-[var(--accent)] focus:outline-none focus:ring-2 focus:ring-[var(--accent-ring)]" />
            {projectName && versionNumber && (
              <p className="mt-1.5 text-[11.5px] text-[var(--ink-muted)]">将创建：<span className="font-medium text-[var(--ink-soft)]">{projectName}V{versionNumber}</span></p>
            )}
          </div>

          {/* 状态 */}
          <div>
            <label className="mb-1.5 block text-[12.5px] font-medium text-[var(--ink-soft)]">状态</label>
            <div className="flex gap-2">
              {([
                { key: 'planned' as VersionStatus, label: '规划中' },
                { key: 'developing' as VersionStatus, label: '开发中' },
              ]).map((opt) => (
                <button key={opt.key} onClick={() => setStatus(opt.key)} className={`flex-1 h-9 rounded-lg border px-3 text-[12.5px] transition-colors ${status === opt.key ? 'border-[var(--accent)] bg-[var(--accent-soft)] text-[var(--accent)]' : 'border-[var(--line)] bg-[var(--bg-card)] text-[var(--ink-soft)] hover:border-[var(--accent)]'}`}>
                  {opt.label}
                </button>
              ))}
            </div>
          </div>
        </div>

        <div className="mt-6 flex justify-end gap-2">
          <button onClick={onClose} className="h-9 rounded-lg border border-[var(--line)] bg-[var(--bg-card)] px-4 text-[13px] text-[var(--ink-soft)] hover:bg-[var(--bg-hover)] transition-colors">取消</button>
          <button onClick={handleSubmit} disabled={!canSubmit} className="h-9 rounded-lg bg-[var(--accent)] px-4 text-[13px] font-medium text-white shadow-[var(--shadow-sm)] hover:bg-[var(--accent-hover)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
            {submitting ? '提交中…' : '创建'}
          </button>
        </div>
      </div>
    </div>
  );
}
