import React, { useEffect, useState } from "react";
import { useAppStore } from "../../store/useAppStore";
import { Card, CardContent, CardHeader, CardTitle } from "../ui/Card";
import { Badge } from "../ui/Badge";
import { api } from "../../api/client";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
  faCircleInfo,
  faDatabase,
  faHashtag,
  faLink,
} from "@fortawesome/free-solid-svg-icons";

export const TorrentDetailsCard = () => {
  const selectedHash = useAppStore((s) => s.selectedHash);
  const torrents = useAppStore((s) => s.torrents);
  const [archiveStatus, setArchiveStatus] = useState<string>("MISSING");

  const torrent = torrents.find((t) => t.hash === selectedHash);

  const refreshArchiveStatus = async (hash: string) => {
    try {
      const response = await api.get(`/api/torrent/archive/status/${hash}`);
      setArchiveStatus(response.data.status);
    } catch (error) {
      setArchiveStatus("MISSING");
    }
  };

  useEffect(() => {
    if (!selectedHash) {
      return;
    }
    api.post("/api/torrent/select", { hash: selectedHash });
    refreshArchiveStatus(selectedHash);
  }, [selectedHash]);

  useEffect(() => {
    const handler = (event: Event) => {
      const detail = (event as CustomEvent<{ hash: string; status: string }>).detail;
      if (detail?.hash === selectedHash && detail.status) {
        setArchiveStatus(detail.status);
      }
    };
    window.addEventListener("archive-status", handler as EventListener);
    return () => window.removeEventListener("archive-status", handler as EventListener);
  }, [selectedHash]);

  if (!torrent) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Selected Torrent</CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-sm text-slate-500">Select a torrent to inspect.</p>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <FontAwesomeIcon icon={faCircleInfo} className="text-slate-400" />
          Selected Torrent
        </CardTitle>
        <Badge
          variant={archiveStatus === "READY" ? "success" : "warn"}
        >
          Archive: {archiveStatus}
        </Badge>
      </CardHeader>
      <CardContent>
        <div className="text-sm text-slate-700">
          <div className="truncate font-semibold text-slate-900" title={torrent.name}>
            {torrent.name}
          </div>
          <div className="mt-2 flex items-center gap-2">
            <FontAwesomeIcon icon={faHashtag} className="text-slate-400" />
            <span className="min-w-0 truncate"> &nbsp; Hash: {torrent.hash}</span>
          </div>
          <div className="flex items-center gap-2">
            <FontAwesomeIcon icon={faDatabase} className="text-slate-400" />
            <span>
              &nbsp; Size: {(torrent.size / (1024 * 1024 * 1024)).toFixed(2)} GB
            </span>
          </div>
          <div className="flex items-center gap-2 truncate" title={torrent.tracker || "-"}>
            <FontAwesomeIcon icon={faLink} className="text-slate-400" />
            <span className="truncate">
              Tracker:{" "}
            {(() => {
              if (!torrent.tracker) {
                return "-";
              }
              try {
                const url = new URL(torrent.tracker);
                return url.hostname;
              } catch {
                return torrent.tracker;
              }
            })()}
            </span>
          </div>
        </div>
      </CardContent>
    </Card>
  );
};
