import React, { useEffect, useState } from "react";
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 { faList, faLock, faUser } 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 ProfilesCard = ({ onApply }: { onApply?: (profile: Profile) => void }) => {
  const [profiles, setProfiles] = useState<Profile[]>([]);
  const [name, setName] = useState("");
  const [allowIp, setAllowIp] = useState("");
  const [delayMs, setDelayMs] = useState(3000);
  const [targetLoops, setTargetLoops] = useState(3);
  const [editingId, setEditingId] = useState<string | null>(null);
  const pushAlert = useUiStore((s) => s.pushAlert);

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

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

  const saveProfile = async () => {
    const payload = {
      name,
      allowIp,
      delayMs,
      targetLoops,
    };
    try {
      if (editingId) {
        const response = await api.put(`/api/profiles/${editingId}`, payload);
        setProfiles((prev) =>
          prev.map((profile) => (profile.id === editingId ? response.data : profile))
        );
        pushAlert({
          title: "Profil güncellendi",
          description: "Profil bilgileri kaydedildi.",
          variant: "success",
        });
        setEditingId(null);
      } else {
        const response = await api.post("/api/profiles", payload);
        setProfiles((prev) => [...prev, response.data]);
        pushAlert({
          title: "Profil kaydedildi",
          description: "Yeni profil eklendi.",
          variant: "success",
        });
      }
      setName("");
      setAllowIp("");
      setDelayMs(3000);
      setTargetLoops(3);
    } catch (error) {
      pushAlert({
        title: "Profil kaydedilemedi",
        description: "Lütfen bilgileri kontrol edip tekrar deneyin.",
        variant: "error",
      });
    }
  };

  const startEdit = (profile: Profile) => {
    setEditingId(profile.id);
    setName(profile.name);
    setAllowIp(profile.allowIp);
    setDelayMs(profile.delayMs);
    setTargetLoops(profile.targetLoops);
  };

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

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <FontAwesomeIcon icon={faUser} className="text-slate-400" />
          Profiles
        </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)} />
            <div className="grid grid-cols-2 gap-2">
              <Input type="number" value={delayMs} onChange={(e) => setDelayMs(Number(e.target.value))} />
              <Input type="number" value={targetLoops} onChange={(e) => setTargetLoops(Number(e.target.value))} />
            </div>
            <Button onClick={saveProfile}>
              {editingId ? "Update Profile" : "Save Profile"}
            </Button>
          </div>
          <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="flex items-center gap-2 text-xs text-slate-500">
                      <span className="flex items-center gap-1">
                        <FontAwesomeIcon icon={faLock} className="text-slate-400" />
                        {profile.allowIp}
                      </span>
                      <span className="flex items-center gap-1">
                        <FontAwesomeIcon icon={faList} className="text-slate-400" />
                        {profile.targetLoops} loops
                      </span>
                    </div>
                  </div>
                <div className="flex items-center gap-2">
                  <Button variant="outline" onClick={() => startEdit(profile)}>
                    Edit
                  </Button>
                  <Button variant="outline" onClick={() => onApply?.(profile)}>
                    Apply
                  </Button>
                  <AlertDialog>
                    <AlertDialogTrigger asChild>
                      <Button variant="ghost">Delete</Button>
                    </AlertDialogTrigger>
                    <AlertDialogContent>
                      <AlertDialogHeader>
                        <AlertDialogTitle>Profil 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>
            ))}
          </div>
        </div>
      </CardContent>
    </Card>
  );
};
