"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { toast } from "sonner";
import {
  Download,
  Pencil,
  Trash2,
  Check,
  X,
  Upload,
  Star,
} from "lucide-react";

interface Version {
  id: string;
  version: string;
  versionCode: number;
  changelog: string;
  downloadType: string;
  filePath: string | null;
  externalUrl: string | null;
  fileSize: number;
  downloadCount: number;
  isLatest: boolean;
  forceUpdate: boolean;
  minVersion: string | null;
  createdAt: string;
}

export function SoftwareVersionTable({
  versions: initialVersions,
}: {
  versions: Version[];
}) {
  const router = useRouter();
  const [editingId, setEditingId] = useState<string | null>(null);

  async function handleSetLatest(versionId: string) {
    const res = await fetch(`/api/software/versions/${versionId}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ isLatest: true }),
    });
    if (res.ok) {
      toast.success("已设为当前下载版本");
      router.refresh();
    } else {
      toast.error("设置失败");
    }
  }

  async function handleDelete(v: Version) {
    if (!confirm(`确定要删除版本 v${v.version} 吗？此操作不可撤销。`)) return;
    const res = await fetch(`/api/software/versions/${v.id}`, {
      method: "DELETE",
    });
    if (res.ok) {
      toast.success("版本已删除");
      router.refresh();
    } else {
      toast.error("删除失败");
    }
  }

  if (initialVersions.length === 0) {
    return (
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>版本</TableHead>
            <TableHead>版本代码</TableHead>
            <TableHead>下载方式</TableHead>
            <TableHead>下载量</TableHead>
            <TableHead>强制更新</TableHead>
            <TableHead>发布时间</TableHead>
            <TableHead>状态</TableHead>
            <TableHead className="text-right">操作</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          <TableRow>
            <TableCell
              colSpan={8}
              className="text-center text-muted-foreground"
            >
              暂无版本，点击上方按钮发布第一个版本
            </TableCell>
          </TableRow>
        </TableBody>
      </Table>
    );
  }

  return (
    <div className="space-y-0">
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>版本</TableHead>
            <TableHead>版本代码</TableHead>
            <TableHead>下载方式</TableHead>
            <TableHead>下载量</TableHead>
            <TableHead>强制更新</TableHead>
            <TableHead>发布时间</TableHead>
            <TableHead>状态</TableHead>
            <TableHead className="text-right">操作</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {initialVersions.map((v) => (
            <TableRow key={v.id}>
              <TableCell className="font-medium">v{v.version}</TableCell>
              <TableCell className="text-muted-foreground">
                {v.versionCode}
              </TableCell>
              <TableCell>
                <Badge variant="secondary">
                  {v.downloadType === "local" ? "本地文件" : "外部链接"}
                </Badge>
              </TableCell>
              <TableCell>
                <span className="flex items-center gap-1">
                  <Download className="h-3.5 w-3.5 text-muted-foreground" />
                  {v.downloadCount}
                </span>
              </TableCell>
              <TableCell>
                {v.forceUpdate ? (
                  <Badge variant="destructive">是</Badge>
                ) : (
                  <span className="text-muted-foreground">否</span>
                )}
              </TableCell>
              <TableCell className="text-muted-foreground">
                {new Date(v.createdAt).toLocaleDateString("zh-CN")}
              </TableCell>
              <TableCell>
                {v.isLatest && <Badge>当前下载</Badge>}
              </TableCell>
              <TableCell>
                <div className="flex items-center justify-end gap-1">
                  {!v.isLatest && (
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-8 w-8"
                      title="设为当前下载版本"
                      onClick={() => handleSetLatest(v.id)}
                    >
                      <Star className="h-3.5 w-3.5" />
                    </Button>
                  )}
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-8 w-8"
                    title="编辑"
                    onClick={() =>
                      setEditingId(editingId === v.id ? null : v.id)
                    }
                  >
                    <Pencil className="h-3.5 w-3.5" />
                  </Button>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-8 w-8 text-destructive hover:text-destructive"
                    title="删除"
                    onClick={() => handleDelete(v)}
                  >
                    <Trash2 className="h-3.5 w-3.5" />
                  </Button>
                </div>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>

      {editingId && (
        <VersionEditPanel
          version={initialVersions.find((v) => v.id === editingId)!}
          onClose={() => setEditingId(null)}
        />
      )}
    </div>
  );
}

function VersionEditPanel({
  version: v,
  onClose,
}: {
  version: Version;
  onClose: () => void;
}) {
  const router = useRouter();
  const [saving, setSaving] = useState(false);

  const [version, setVersion] = useState(v.version);
  const [versionCode, setVersionCode] = useState(v.versionCode.toString());
  const [changelog, setChangelog] = useState(v.changelog);
  const [downloadType, setDownloadType] = useState(v.downloadType);
  const [externalUrl, setExternalUrl] = useState(v.externalUrl || "");
  const [forceUpdate, setForceUpdate] = useState(v.forceUpdate);
  const [minVersion, setMinVersion] = useState(v.minVersion || "");
  const [filePath, setFilePath] = useState(v.filePath || "");
  const [fileSize, setFileSize] = useState(v.fileSize);
  const [uploading, setUploading] = useState(false);

  async function handleFileUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploading(true);
    const formData = new FormData();
    formData.append("file", file);
    const res = await fetch("/api/upload", { method: "POST", body: formData });
    if (res.ok) {
      const data = await res.json();
      setFilePath(data.filePath);
      setFileSize(data.size);
      toast.success(`文件 ${data.originalName} 上传成功`);
    } else {
      toast.error("文件上传失败");
    }
    setUploading(false);
  }

  async function handleSave() {
    setSaving(true);
    if (downloadType === "local" && !filePath) {
      toast.error("请先上传文件");
      setSaving(false);
      return;
    }
    if (downloadType === "url" && !externalUrl) {
      toast.error("请输入外部链接");
      setSaving(false);
      return;
    }

    const res = await fetch(`/api/software/versions/${v.id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        version,
        versionCode: Number(versionCode),
        changelog,
        downloadType,
        filePath: downloadType === "local" ? filePath : null,
        externalUrl: downloadType === "url" ? externalUrl : null,
        fileSize,
        forceUpdate,
        minVersion: minVersion || null,
      }),
    });

    if (res.ok) {
      toast.success("版本更新成功");
      onClose();
      router.refresh();
    } else {
      const err = await res.json();
      toast.error(err.error || "更新失败");
    }
    setSaving(false);
  }

  return (
    <div className="border-t bg-muted/30 p-6">
      <div className="mx-auto max-w-2xl space-y-4">
        <div className="flex items-center justify-between">
          <h3 className="font-semibold">编辑版本 v{v.version}</h3>
          <Button variant="ghost" size="icon" className="h-8 w-8" onClick={onClose}>
            <X className="h-4 w-4" />
          </Button>
        </div>

        <div className="grid gap-4 sm:grid-cols-2">
          <div className="space-y-2">
            <Label>版本号</Label>
            <Input value={version} onChange={(e) => setVersion(e.target.value)} />
          </div>
          <div className="space-y-2">
            <Label>版本代码</Label>
            <Input
              type="number"
              value={versionCode}
              onChange={(e) => setVersionCode(e.target.value)}
            />
          </div>
        </div>

        <div className="space-y-2">
          <Label>最低兼容版本</Label>
          <Input
            value={minVersion}
            onChange={(e) => setMinVersion(e.target.value)}
            placeholder="可选"
          />
        </div>

        <div className="space-y-2">
          <Label>更新日志</Label>
          <Textarea
            value={changelog}
            onChange={(e) => setChangelog(e.target.value)}
            rows={4}
          />
        </div>

        <div className="space-y-3">
          <Label>下载方式</Label>
          <div className="flex gap-3">
            <Button
              type="button"
              size="sm"
              variant={downloadType === "local" ? "default" : "outline"}
              onClick={() => setDownloadType("local")}
            >
              上传文件
            </Button>
            <Button
              type="button"
              size="sm"
              variant={downloadType === "url" ? "default" : "outline"}
              onClick={() => setDownloadType("url")}
            >
              外部链接
            </Button>
          </div>

          {downloadType === "local" ? (
            <div className="space-y-2">
              <Label
                htmlFor={`edit-file-${v.id}`}
                className="flex cursor-pointer items-center gap-2 rounded-lg border-2 border-dashed px-4 py-3 text-sm transition-colors hover:border-primary"
              >
                <Upload className="h-4 w-4" />
                {uploading
                  ? "上传中..."
                  : filePath
                    ? "重新选择文件"
                    : "选择文件"}
              </Label>
              <Input
                id={`edit-file-${v.id}`}
                type="file"
                className="hidden"
                onChange={handleFileUpload}
              />
              {filePath && (
                <p className="text-xs text-muted-foreground">
                  文件: {filePath} ({(fileSize / 1024).toFixed(1)} KB)
                </p>
              )}
            </div>
          ) : (
            <div className="space-y-2">
              <Input
                value={externalUrl}
                onChange={(e) => setExternalUrl(e.target.value)}
                placeholder="https://..."
              />
              {externalUrl && (
                <p className="truncate text-xs text-muted-foreground">
                  当前: {externalUrl}
                </p>
              )}
            </div>
          )}
        </div>

        <label className="flex items-center gap-2 text-sm">
          <input
            type="checkbox"
            checked={forceUpdate}
            onChange={(e) => setForceUpdate(e.target.checked)}
            className="h-4 w-4 rounded border-input"
          />
          强制更新
        </label>

        <div className="flex gap-2 pt-2">
          <Button size="sm" onClick={handleSave} disabled={saving}>
            <Check className="mr-1.5 h-3.5 w-3.5" />
            {saving ? "保存中..." : "保存修改"}
          </Button>
          <Button size="sm" variant="outline" onClick={onClose}>
            取消
          </Button>
        </div>
      </div>
    </div>
  );
}
