"use client";

import { faPlus, faInfoCircle } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useEffect, useState } from "react";
import IconPicker from "@/components/IconPicker";
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 { getIcon } from "@/lib/icons";
import type { AboutCard } from "@/types/models";
import AdminCard from "@/components/admin/AdminCard";
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 AdminDataGrid from "@/components/admin/AdminDataGrid";
import AdminEmptyState from "@/components/admin/AdminEmptyState";
import AdminFormModal from "@/components/admin/AdminFormModal";
import AdminConfirmDialog from "@/components/admin/AdminConfirmDialog";
import AdminEditDeleteButtons from "@/components/admin/AdminEditDeleteButtons";
import AdminBadge from "@/components/admin/AdminBadge";
import AdminLoadingState from "@/components/admin/AdminLoadingState";
import { adminFetch } from "@/lib/adminFetch";

export default function AboutTab() {
  const [cards, setCards] = useState<AboutCard[]>([]);
  const [newCard, setNewCard] = useState<AboutCard>({
    title: "",
    description: "",
    icon: "Lightbulb",
  });
  const [editingId, setEditingId] = useState<number | null>(null);
  const [aboutImage, setAboutImage] = useState<string>("");
  const [loading, setLoading] = useState(true);
  const [showEditor, setShowEditor] = useState(false);
  const [deleteConfirm, setDeleteConfirm] = useState<{
    isOpen: boolean;
    id: number | null;
  }>({ isOpen: false, id: null });
  const { toast, showSuccess, showError, hideToast } = useAdminToast();
  const { uploadImage, deleteImage, isUploading } = useImageUpload({
    onUploadSuccess: (url) => setAboutImage(url),
    onDeleteSuccess: () => setAboutImage(""),
  });

  useEffect(() => {
    let cancelled = false;
    Promise.all([fetch("/api/about"), fetch("/api/about/sectionmeta")])
      .then(async ([cardsRes, metaRes]) => {
        if (cancelled) return;
        setCards(await cardsRes.json());
        const meta = await metaRes.json();
        setAboutImage(meta?.image || "");
        setLoading(false);
      })
      .catch(() => {
        if (!cancelled) {
          showError("Failed to load about section");
          setLoading(false);
        }
      });
    return () => {
      cancelled = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const resetForm = () => {
    setNewCard({ title: "", description: "", icon: "Lightbulb" });
    setEditingId(null);
    setShowEditor(false);
  };

  const handleSubmit = async () => {
    try {
      const payload = editingId ? { id: editingId, ...newCard } : newCard;
      const response = await adminFetch("/api/about", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      if (!response.ok) throw new Error();
      const saved = await response.json();
      setCards((prev) =>
        editingId ? prev.map((c) => (c.id === editingId ? saved : c)) : [...prev, saved],
      );
      showSuccess(editingId ? "Card updated successfully!" : "Card saved successfully!");
      resetForm();
    } catch {
      showError("Failed to save card. Please try again.");
    }
  };

  const handleDelete = async (id: number) => {
    try {
      const response = await adminFetch("/api/about", {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id }),
      });
      if (!response.ok) throw new Error();
      setCards((prev) => prev.filter((c) => c.id !== id));
      showSuccess("Card deleted successfully!");
    } catch {
      showError("Failed to delete card. Please try again.");
    } finally {
      setDeleteConfirm({ isOpen: false, id: null });
    }
  };

  const startEdit = (card: AboutCard) => {
    setNewCard({ title: card.title, description: card.description, icon: card.icon });
    setEditingId(card.id!);
    setShowEditor(true);
  };

  const handleImageChange = async (file: File | File[]) => {
    const url = await uploadImage(file);
    if (url) {
      const res = await adminFetch("/api/about/sectionmeta", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ image: url }),
      });
      if (res.ok) {
        const data = await res.json();
        setAboutImage(data.image);
      }
    }
  };

  const handleImageDelete = async () => {
    if (!aboutImage) return;
    await deleteImage(aboutImage);
    const res = await adminFetch("/api/about/sectionmeta", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ image: null }),
    });
    if (res.ok) {
      const data = await res.json();
      setAboutImage(data.image);
    }
  };

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

  const mainCard = cards[0];
  const otherCards = cards.slice(1);

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

      <AdminConfirmDialog
        isOpen={deleteConfirm.isOpen}
        onClose={() => setDeleteConfirm({ isOpen: false, id: null })}
        onConfirm={() => deleteConfirm.id && handleDelete(deleteConfirm.id)}
        title="Delete card"
        message="Are you sure you want to delete this card? This action cannot be undone."
      />

      <div className="space-y-6">
        <AdminCard>
          <AdminSection title="Section banner image">
            <ImageUpload
              onImageUpload={handleImageChange}
              onImageDelete={handleImageDelete}
              currentImage={aboutImage}
              disabled={isUploading}
              className="w-full"
            />
          </AdminSection>
        </AdminCard>

        {mainCard && (
          <AdminCard className="ring-1 ring-inset ring-indigo-500/30">
            <div className="relative flex flex-col items-start gap-5 md:flex-row md:items-center">
              <div className="flex h-14 w-14 shrink-0 items-center justify-center rounded-xl bg-indigo-500/10 text-indigo-400">
                <FontAwesomeIcon icon={getIcon(mainCard.icon)} className="h-6 w-6" />
              </div>
              <div className="flex-1 min-w-0">
                <div className="mb-1 flex items-center gap-2">
                  <h3 className="text-lg font-semibold text-slate-100">
                    {mainCard.title}
                  </h3>
                  <AdminBadge variant="accent">Main card</AdminBadge>
                </div>
                <p className="text-sm text-slate-400">{mainCard.description}</p>
              </div>
              <AdminEditDeleteButtons
                onEdit={() => startEdit(mainCard)}
                onDelete={() => setDeleteConfirm({ isOpen: true, id: mainCard.id! })}
              />
            </div>
          </AdminCard>
        )}

        <AdminCard
          header={
            <div className="flex items-center justify-between">
              <div>
                <h3 className="text-sm font-semibold text-slate-100">Feature cards</h3>
                <p className="text-xs text-slate-400">Up to 3 additional cards</p>
              </div>
              {otherCards.length < 3 && (
                <AdminButton
                  variant="primary"
                  size="sm"
                  icon={faPlus}
                  onClick={() => {
                    setEditingId(null);
                    setNewCard({ title: "", description: "", icon: "Lightbulb" });
                    setShowEditor(true);
                  }}
                >
                  Add card
                </AdminButton>
              )}
            </div>
          }
        >
          {otherCards.length === 0 && !mainCard ? (
            <AdminEmptyState
              title="No cards yet"
              description="Add your first about card to get started"
              icon={faInfoCircle}
              action={{ label: "Add card", onClick: () => setShowEditor(true) }}
            />
          ) : (
            <AdminDataGrid columns={3} gap="md">
              {otherCards.map((card) => (
                <div
                  key={card.id}
                  className="group relative rounded-lg border border-slate-800 bg-slate-900/60 p-5"
                >
                  <div className="mb-3 flex h-12 w-12 items-center justify-center rounded-lg bg-indigo-500/10 text-indigo-400">
                    <FontAwesomeIcon icon={getIcon(card.icon)} className="h-5 w-5" />
                  </div>
                  <h3 className="mb-1 text-base font-semibold text-slate-100">
                    {card.title}
                  </h3>
                  <p className="text-sm text-slate-400">{card.description}</p>
                  <div className="absolute right-2 top-2 opacity-0 transition-opacity group-hover:opacity-100">
                    <AdminEditDeleteButtons
                      onEdit={() => startEdit(card)}
                      onDelete={() => setDeleteConfirm({ isOpen: true, id: card.id! })}
                      size="sm"
                    />
                  </div>
                </div>
              ))}
            </AdminDataGrid>
          )}
        </AdminCard>
      </div>

      <AdminFormModal
        isOpen={showEditor}
        onClose={resetForm}
        title={editingId ? "Edit card" : "Add new card"}
        onSubmit={handleSubmit}
        submitLabel={editingId ? "Save changes" : "Add card"}
      >
        <AdminInput
          label="Title"
          placeholder="Card title"
          value={newCard.title}
          onChange={(e) => setNewCard({ ...newCard, title: e.target.value })}
          required
        />
        <AdminTextarea
          label="Description"
          placeholder="Card description"
          value={newCard.description}
          onChange={(e) => setNewCard({ ...newCard, description: e.target.value })}
          rows={4}
          required
        />
        <div>
          <label className="mb-1.5 block text-sm font-medium text-slate-300">
            Icon
          </label>
          <div className="flex items-center gap-3">
            <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-indigo-500/10 text-indigo-400">
              <FontAwesomeIcon icon={getIcon(newCard.icon)} className="h-5 w-5" />
            </div>
            <div className="flex-1">
              <IconPicker
                value={newCard.icon}
                onChange={(icon) => setNewCard({ ...newCard, icon })}
              />
            </div>
          </div>
        </div>
      </AdminFormModal>
    </>
  );
}
