import React, { useEffect, useState } from "react";
import { useAppStore } from "../../store/useAppStore";
import { Card, CardContent, CardHeader, CardTitle } from "../ui/Card";
import { Input } from "../ui/Input";
import { Button } from "../ui/Button";
import { api } from "../../api/client";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faCircleInfo, faPlay, faStop, faTrash } from "@fortawesome/free-solid-svg-icons";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "../ui/AlertDialog";
import { useUiStore } from "../../store/useUiStore";

interface Profile {
  id: string;
  name: string;
  allowIp: string;
  delayMs: number;
  targetLoops: number;
}

export const LoopSetupCard = () => {
  const selectedHash = useAppStore((s) => s.selectedHash);
  const loopForm = useAppStore((s) => s.loopForm);
  const setLoopForm = useAppStore((s) => s.setLoopForm);
  const jobs = useAppStore((s) => s.jobs);
  const pushAlert = useUiStore((s) => s.pushAlert);

  const [profiles, setProfiles] = useState<Profile[]>([]);
  const [name, setName] = useState("");
  const [allowIp, setAllowIp] = useState(loopForm.allowIp || "");
  const [delayMs, setDelayMs] = useState(loopForm.delayMs ?? 3000);
  const [targetLoops, setTargetLoops] = useState(loopForm.targetLoops ?? 3);
  const isRunning = Boolean(selectedHash && jobs.some((job) => job.torrentHash === selectedHash && job.status === "RUNNING"));

  const isRunningPreset = (profile: Profile) => {
    if (!selectedHash) return false;
    const job = jobs.find((j) => j.torrentHash === selectedHash && j.status === "RUNNING");
    if (!job) return false;
    if (job.profileId) {
      return job.profileId === profile.id;
    }
    return (
      job.allowIp === profile.allowIp &&
      job.delayMs === profile.delayMs &&
      job.targetLoops === profile.targetLoops
    );
  };

  const formatDelay = (ms: number) => `${Math.round(ms / 60000)} dk`;

  const loadProfiles = async () => {
    const response = await api.get("/api/profiles");
    setProfiles(response.data);
  };

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

  useEffect(() => {
    setAllowIp(loopForm.allowIp || "");
    setDelayMs(loopForm.delayMs ?? 3000);
    setTargetLoops(loopForm.targetLoops ?? 3);
  }, [loopForm]);

  const saveProfile = async () => {
    const payload = {
      name: name.trim(),
      allowIp: allowIp.trim(),
      delayMs,
      targetLoops,
    };
    if (!payload.name || !payload.allowIp) {
      pushAlert({
        title: "Eksik bilgi",
        description: "Preset name ve Allow IP zorunlu.",
        variant: "warn",
      });
      return;
    }
    try {
      {
        const response = await api.post("/api/profiles", payload);
        setProfiles((prev) => [...prev, response.data]);
        pushAlert({
          title: "Setup kaydedildi",
          description: "Yeni setup eklendi.",
          variant: "success",
        });
      }
      setLoopForm({
        allowIp: payload.allowIp,
        delayMs: payload.delayMs,
        targetLoops: payload.targetLoops,
      });
      setName("");
    } catch (error) {
      pushAlert({
        title: "Kaydedilemedi",
        description: "Lütfen bilgileri kontrol edip tekrar deneyin.",
        variant: "error",
      });
    }
  };

  const stopLoop = async () => {
    if (!selectedHash) {
      return;
    }
    try {
      await api.post("/api/loop/stop-by-hash", { hash: selectedHash });
      pushAlert({
        title: "Loop durduruldu",
        description: "Seçili torrent için loop durduruldu.",
        variant: "success",
      });
    } catch (error) {
      pushAlert({
        title: "Durdurma başarısız",
        description: "Loop durdurulamadı.",
        variant: "error",
      });
    }
  };

  const applyProfile = async (profile: Profile) => {
    if (!selectedHash) {
      pushAlert({
        title: "Torrent seçilmedi",
        description: "Önce bir torrent seçin.",
        variant: "warn",
      });
      return;
    }
    try {
      await api.post("/api/loop/start", {
        hash: selectedHash,
        allowIp: profile.allowIp,
        targetLoops: profile.targetLoops,
        delayMs: profile.delayMs,
        profileName: profile.name,
        profileId: profile.id,
      });
      setLoopForm({
        allowIp: profile.allowIp,
        delayMs: profile.delayMs,
        targetLoops: profile.targetLoops,
      });
      pushAlert({
        title: "Loop başlatıldı",
        description: "Seçilen setup ile loop başlatıldı.",
        variant: "success",
      });
    } catch (error: any) {
      const apiError = error?.response?.data?.error;
      pushAlert({
        title: "Loop başlatılamadı",
        description: apiError || "Sunucu loglarını kontrol edin.",
        variant: "error",
      });
    }
  };

  const removeProfile = async (profileId: string) => {
    try {
      await api.delete(`/api/profiles/${profileId}`);
      setProfiles((prev) => prev.filter((profile) => profile.id !== profileId));
      pushAlert({
        title: "Setup silindi",
        description: "Setup listeden kaldırıldı.",
        variant: "success",
      });
    } catch (error) {
      pushAlert({
        title: "Silme başarısız",
        description: "Setup silinemedi.",
        variant: "error",
      });
    }
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <FontAwesomeIcon icon={faCircleInfo} className="text-slate-400" />
          Loop Setup
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="grid gap-3 text-sm">
          <div className="grid gap-2">
            <Input
              placeholder="Preset name"
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
            <Input
              placeholder="Allow IP"
              value={allowIp}
              onChange={(e) => {
                setAllowIp(e.target.value);
                setLoopForm({ allowIp: e.target.value });
              }}
            />
            <div className="grid grid-cols-2 gap-2">
              <Input
                type="number"
                placeholder="Delay (ms)"
                value={delayMs}
                onChange={(e) => {
                  const value = Number(e.target.value);
                  setDelayMs(value);
                  setLoopForm({ delayMs: value });
                }}
              />
              <Input
                type="number"
                placeholder="Loops"
                value={targetLoops}
                onChange={(e) => {
                  const value = Number(e.target.value);
                  setTargetLoops(value);
                  setLoopForm({ targetLoops: value });
                }}
              />
            </div>
            <Button onClick={saveProfile} className="w-full">
              Save Setup
            </Button>
          </div>

          <div className="border-t border-slate-200 pt-3">
            <div className="space-y-2">
              {profiles.map((profile) => (
                <div
                  key={profile.id}
                  className="flex items-center justify-between rounded-md border border-slate-200 bg-white px-3 py-2"
                >
                  <div>
                    <div className="font-semibold">{profile.name}</div>
                    <div className="text-xs text-slate-500">
                      {profile.allowIp} • {profile.targetLoops} loops • {formatDelay(profile.delayMs)}
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <Button
                      variant="outline"
                      className="h-8 w-8 px-0"
                      onClick={() => (isRunningPreset(profile) ? stopLoop() : applyProfile(profile))}
                      title={isRunningPreset(profile) ? "Stop" : "Apply"}
                    >
                      <FontAwesomeIcon icon={isRunningPreset(profile) ? faStop : faPlay} />
                    </Button>
                    <AlertDialog>
                      <AlertDialogTrigger asChild>
                        <Button variant="ghost" className="h-8 w-8 px-0" title="Delete">
                          <FontAwesomeIcon icon={faTrash} />
                        </Button>
                      </AlertDialogTrigger>
                      <AlertDialogContent>
                        <AlertDialogHeader>
                          <AlertDialogTitle>Setup silinsin mi?</AlertDialogTitle>
                          <AlertDialogDescription>
                            Bu işlem geri alınamaz.
                          </AlertDialogDescription>
                        </AlertDialogHeader>
                        <AlertDialogFooter>
                          <AlertDialogCancel>İptal</AlertDialogCancel>
                          <AlertDialogAction onClick={() => removeProfile(profile.id)}>
                            Sil
                          </AlertDialogAction>
                        </AlertDialogFooter>
                      </AlertDialogContent>
                    </AlertDialog>
                  </div>
                </div>
              ))}
              {profiles.length === 0 && (
                <div className="rounded-md border border-dashed border-slate-200 bg-white px-3 py-2 text-xs text-slate-500">
                  Henüz kayıtlı setup yok.
                </div>
              )}
            </div>
          </div>
        </div>
      </CardContent>
    </Card>
  );
};
