"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { toast } from "sonner";
import { Upload } from "lucide-react";

interface ReleaseFormProps {
  addons: { id: string; name: string }[];
}

export function ReleaseForm({ addons }: ReleaseFormProps) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [downloadType, setDownloadType] = useState("local");
  const [uploadedFilePath, setUploadedFilePath] = useState("");
  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();
      setUploadedFilePath(data.filePath);
      toast.success(`文件 ${data.originalName} 上传成功`);
    } else {
      toast.error("文件上传失败");
    }
    setUploading(false);
  }

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setLoading(true);

    const formData = new FormData(e.currentTarget);
    const data = {
      addonId: formData.get("addonId"),
      version: formData.get("version"),
      changelog: formData.get("changelog"),
      downloadType,
      filePath: downloadType === "local" ? uploadedFilePath : null,
      externalUrl:
        downloadType === "url" ? formData.get("externalUrl") : null,
      gameVersion: formData.get("gameVersion"),
    };

    if (downloadType === "local" && !uploadedFilePath) {
      toast.error("请先上传文件");
      setLoading(false);
      return;
    }

    const res = await fetch("/api/releases", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    });

    if (res.ok) {
      toast.success("版本发布成功");
      router.push("/admin/releases");
      router.refresh();
    } else {
      const err = await res.json();
      toast.error(err.error || "发布失败");
    }

    setLoading(false);
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>发布新版本</CardTitle>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="grid gap-4 md:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="addonId">选择插件 *</Label>
              <Select name="addonId" required>
                <SelectTrigger>
                  <SelectValue placeholder="选择一个插件" />
                </SelectTrigger>
                <SelectContent>
                  {addons.map((addon) => (
                    <SelectItem key={addon.id} value={addon.id}>
                      {addon.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label htmlFor="version">版本号 *</Label>
              <Input
                id="version"
                name="version"
                required
                placeholder="1.0.0"
              />
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="gameVersion">兼容游戏版本</Label>
            <Input
              id="gameVersion"
              name="gameVersion"
              placeholder="11.1.0"
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="changelog">更新日志</Label>
            <Textarea
              id="changelog"
              name="changelog"
              rows={6}
              placeholder="- 新增功能 A&#10;- 修复问题 B"
            />
          </div>

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

            {downloadType === "local" ? (
              <div className="space-y-2">
                <div className="flex items-center gap-4">
                  <Label
                    htmlFor="file"
                    className="flex cursor-pointer items-center gap-2 rounded-lg border-2 border-dashed px-6 py-4 transition-colors hover:border-primary"
                  >
                    <Upload className="h-5 w-5" />
                    {uploading
                      ? "上传中..."
                      : uploadedFilePath
                        ? "重新选择文件"
                        : "选择文件"}
                  </Label>
                  <Input
                    id="file"
                    type="file"
                    className="hidden"
                    accept=".zip,.rar,.7z,.tar.gz"
                    onChange={handleFileUpload}
                  />
                </div>
                {uploadedFilePath && (
                  <p className="text-sm text-muted-foreground">
                    已上传: {uploadedFilePath}
                  </p>
                )}
              </div>
            ) : (
              <div className="space-y-2">
                <Label htmlFor="externalUrl">下载链接</Label>
                <Input
                  id="externalUrl"
                  name="externalUrl"
                  type="url"
                  placeholder="https://github.com/user/repo/releases/download/v1.0.0/addon.zip"
                />
              </div>
            )}
          </div>

          <div className="flex gap-3">
            <Button type="submit" disabled={loading}>
              {loading ? "发布中..." : "发布版本"}
            </Button>
            <Button
              type="button"
              variant="outline"
              onClick={() => router.back()}
            >
              取消
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}
