import React, { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "../ui/Card";
import { Button } from "../ui/Button";
import { api } from "../../api/client";
import { useAppStore } from "../../store/useAppStore";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faCircleInfo, faTriangleExclamation, faUpload } from "@fortawesome/free-solid-svg-icons";
import { useUiStore } from "../../store/useUiStore";

export const AdvancedUploadCard = () => {
  const selectedHash = useAppStore((s) => s.selectedHash);
  const [open, setOpen] = useState(false);
  const [file, setFile] = useState<File | null>(null);
  const pushAlert = useUiStore((s) => s.pushAlert);

  const upload = async () => {
    if (!selectedHash) {
      pushAlert({
        title: "Torrent seçilmedi",
        description: "Önce bir torrent seçmelisiniz.",
        variant: "warn",
      });
      return;
    }
    if (!file) {
      pushAlert({
        title: "Dosya seçilmedi",
        description: "Lütfen bir .torrent dosyası seçin.",
        variant: "warn",
      });
      return;
    }
    try {
      const form = new FormData();
      form.append("file", file);
      form.append("hash", selectedHash);
      const response = await api.post("/api/torrent/archive/upload", form, {
        headers: { "Content-Type": "multipart/form-data" },
      });
      if (response.data?.added) {
        pushAlert({
          title: "Yükleme başarılı",
          description: "Torrent qBittorrent'a eklendi.",
          variant: "success",
        });
      } else {
        pushAlert({
          title: "Yükleme yapıldı",
          description: "Torrent arşive alındı, qBittorrent'a eklenemedi.",
          variant: "warn",
        });
      }
      if (selectedHash) {
        const statusResponse = await api.get(
          `/api/torrent/archive/status/${selectedHash}`
        );
        window.dispatchEvent(
          new CustomEvent("archive-status", {
            detail: { hash: selectedHash, status: statusResponse.data?.status },
          })
        );
      }
    } catch (error: any) {
      const apiError = error?.response?.data?.error;
      pushAlert({
        title: "Yükleme başarısız",
        description: apiError || "Sunucu loglarını kontrol edin.",
        variant: "error",
      });
    }
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <FontAwesomeIcon icon={faCircleInfo} className="text-slate-400" />
          Advanced
        </CardTitle>
        <Button variant="ghost" onClick={() => setOpen(!open)}>
          {open ? "Hide" : "Show"}
        </Button>
      </CardHeader>
      {open && (
        <CardContent>
          <div className="space-y-3 text-sm">
            <div className="flex items-center gap-2 text-slate-600">
              <FontAwesomeIcon icon={faCircleInfo} className="text-slate-400" />
              Upload a .torrent file if magnet metadata fetch fails.
            </div>
            {!selectedHash && (
              <div className="flex items-center gap-2 text-amber-700">
                <FontAwesomeIcon icon={faTriangleExclamation} />
                Önce bir torrent seçmelisiniz.
              </div>
            )}
            <input
              type="file"
              accept=".torrent"
              onChange={(e) => setFile(e.target.files?.[0] ?? null)}
            />
            <Button onClick={upload} disabled={!file || !selectedHash}>
              <FontAwesomeIcon icon={faUpload} className="mr-2" />
              Upload Torrent
            </Button>
          </div>
        </CardContent>
      )}
    </Card>
  );
};
