"use client";

import { faPlus, faTrash } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useEffect, useState } from "react";
import ImageUpload from "@/components/ui/ImageUpload";
import Toast from "@/components/ui/Toast";
import { useAdminToast } from "@/hooks/admin/useAdminToast";
import { useImageUpload } from "@/hooks/admin/useImageUpload";
import AdminCard from "@/components/admin/AdminCard";
import AdminForm from "@/components/admin/AdminForm";
import AdminSection from "@/components/admin/AdminSection";
import AdminInput from "@/components/admin/AdminInput";
import AdminTextarea from "@/components/admin/AdminTextarea";
import AdminButton from "@/components/admin/AdminButton";
import AdminLoadingState from "@/components/admin/AdminLoadingState";
import { adminFetch } from "@/lib/adminFetch";
import type { HeroState } from "@/types/models";

export default function HeroTab() {
  const [hero, setHero] = useState<HeroState>({
    title: "",
    description: "",
    background: null,
    buttons: [],
  });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const { toast, showSuccess, showError, hideToast } = useAdminToast();
  const { uploadImage, deleteImage, isUploading } = useImageUpload({
    onUploadSuccess: (url) => setHero((prev) => ({ ...prev, background: url })),
    onDeleteSuccess: () => setHero((prev) => ({ ...prev, background: null })),
  });

  useEffect(() => {
    let cancelled = false;
    fetch("/api/hero")
      .then((res) => res.json())
      .then((data) => {
        if (!cancelled) {
          setHero(
            data || { title: "", description: "", background: null, buttons: [] },
          );
          setLoading(false);
        }
      })
      .catch(() => {
        if (!cancelled) {
          showError("Failed to load hero section");
          setLoading(false);
        }
      });
    return () => {
      cancelled = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    try {
      const formData = new FormData();
      formData.append("title", hero.title);
      formData.append("description", hero.description);
      if (hero.background) formData.append("background", hero.background);
      formData.append("buttons", JSON.stringify(hero.buttons));

      const response = await adminFetch("/api/hero", { method: "POST", body: formData });
      if (!response.ok) throw new Error("Failed to update hero section");
      showSuccess("Hero section updated successfully!");
    } catch {
      showError("Failed to update hero section. Please try again.");
    } finally {
      setSaving(false);
    }
  };

  if (loading) return <AdminLoadingState message="Loading hero section..." />;

  return (
    <>
      {toast && <Toast message={toast.message} type={toast.type} onClose={hideToast} />}

      <AdminCard>
        <AdminForm onSubmit={handleSave}>
          <div className="grid grid-cols-1 gap-8 lg:grid-cols-2">
            <div className="space-y-6">
              <AdminSection title="Content">
                <AdminInput
                  label="Title"
                  placeholder="Enter hero title"
                  value={hero.title}
                  onChange={(e) => setHero({ ...hero, title: e.target.value })}
                  required
                />
                <AdminTextarea
                  label="Description"
                  placeholder="Enter hero description"
                  value={hero.description}
                  onChange={(e) => setHero({ ...hero, description: e.target.value })}
                  rows={5}
                />
              </AdminSection>

              <AdminSection title="Call-to-action buttons">
                <div className="space-y-3">
                  {hero.buttons.map((button, index) => (
                    <div
                      key={index}
                      className="flex items-center gap-2 rounded-lg border border-slate-800 bg-slate-900/60 p-3"
                    >
                      <AdminInput
                        placeholder="Button label"
                        value={button.label}
                        onChange={(e) => {
                          const updated = [...hero.buttons];
                          updated[index].label = e.target.value;
                          setHero({ ...hero, buttons: updated });
                        }}
                        className="flex-1"
                      />
                      <AdminInput
                        placeholder="Button URL"
                        value={button.url}
                        onChange={(e) => {
                          const updated = [...hero.buttons];
                          updated[index].url = e.target.value;
                          setHero({ ...hero, buttons: updated });
                        }}
                        className="flex-1"
                      />
                      <button
                        type="button"
                        onClick={() => {
                          const updated = hero.buttons.filter((_, i) => i !== index);
                          setHero({ ...hero, buttons: updated });
                        }}
                        className="inline-flex h-9 w-9 items-center justify-center rounded-md text-slate-400 transition-colors hover:bg-rose-500/10 hover:text-rose-400"
                        title="Remove button"
                        aria-label="Remove button"
                      >
                        <FontAwesomeIcon icon={faTrash} className="h-3.5 w-3.5" />
                      </button>
                    </div>
                  ))}
                </div>
                <AdminButton
                  type="button"
                  variant="secondary"
                  onClick={() =>
                    setHero({
                      ...hero,
                      buttons: [...hero.buttons, { label: "", url: "" }],
                    })
                  }
                  icon={faPlus}
                >
                  Add button
                </AdminButton>
              </AdminSection>
            </div>

            <div>
              <AdminSection title="Background image">
                <ImageUpload
                  onImageUpload={async (file) => {
                    await uploadImage(file);
                  }}
                  onImageDelete={async () => {
                    if (hero.background) {
                      await deleteImage(hero.background);
                    }
                  }}
                  currentImage={hero.background}
                  disabled={isUploading}
                  className="w-full"
                />
              </AdminSection>
            </div>
          </div>

          <div className="-mx-6 -mb-6 mt-8 flex justify-end border-t border-slate-800 px-6 py-4">
            <AdminButton type="submit" variant="primary" isLoading={saving}>
              Save hero section
            </AdminButton>
          </div>
        </AdminForm>
      </AdminCard>
    </>
  );
}
