"use client";

import { faAddressCard, faPlus } from "@fortawesome/free-solid-svg-icons";
import { useEffect, useState } from "react";
import Toast from "@/components/ui/Toast";
import { useAdminToast } from "@/hooks/admin/useAdminToast";
import type { ContactCard } from "@/types/models";
import AdminPageHeader from "@/components/admin/AdminPageHeader";
import AdminCard from "@/components/admin/AdminCard";
import AdminInput from "@/components/admin/AdminInput";
import AdminEmptyState from "@/components/admin/AdminEmptyState";
import AdminConfirmDialog from "@/components/admin/AdminConfirmDialog";
import AdminFormModal from "@/components/admin/AdminFormModal";
import AdminDataTable from "@/components/admin/AdminDataTable";
import AdminEditDeleteButtons from "@/components/admin/AdminEditDeleteButtons";
import AdminLoadingState from "@/components/admin/AdminLoadingState";
import { adminFetch } from "@/lib/adminFetch";

const emptyCard = { name: "", phone: "", email: "" };

export default function AdminContactCards() {
  const [cards, setCards] = useState<ContactCard[]>([]);
  const [loading, setLoading] = useState(true);
  const [formData, setFormData] = useState(emptyCard);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [showEditor, setShowEditor] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [deleteConfirm, setDeleteConfirm] = useState<{
    isOpen: boolean;
    id: number | null;
  }>({ isOpen: false, id: null });
  const { toast, showSuccess, showError, hideToast } = useAdminToast();

  useEffect(() => {
    fetchCards();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const fetchCards = async () => {
    try {
      const res = await fetch("/api/contact-cards");
      setCards(await res.json());
    } catch {
      showError("Failed to load contact cards");
    } finally {
      setLoading(false);
    }
  };

  const resetForm = () => {
    setFormData(emptyCard);
    setEditingId(null);
    setShowEditor(false);
  };

  const handleSubmit = async () => {
    setIsSaving(true);
    try {
      const res = await adminFetch(
        "/api/contact-cards" + (editingId ? `/${editingId}` : ""),
        {
          method: editingId ? "PUT" : "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(formData),
        },
      );
      if (!res.ok) throw new Error();
      showSuccess(`Contact card ${editingId ? "updated" : "created"} successfully!`);
      await fetchCards();
      resetForm();
    } catch {
      showError("Failed to save contact card");
    } finally {
      setIsSaving(false);
    }
  };

  const handleDelete = async (id: number) => {
    try {
      const res = await adminFetch(`/api/contact-cards/${id}`, { method: "DELETE" });
      if (!res.ok) throw new Error();
      showSuccess("Contact card deleted successfully!");
      await fetchCards();
    } catch {
      showError("Failed to delete contact card");
    } finally {
      setDeleteConfirm({ isOpen: false, id: null });
    }
  };

  const startEdit = (card: ContactCard) => {
    setFormData({ name: card.name, phone: card.phone, email: card.email });
    setEditingId(card.id!);
    setShowEditor(true);
  };

  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 contact card"
        message="Are you sure you want to delete this contact card? This action cannot be undone."
      />

      <AdminPageHeader
        title="Contact Cards"
        description="Manage contact information cards displayed on your website"
        action={{
          label: "Add card",
          onClick: () => {
            setEditingId(null);
            setFormData(emptyCard);
            setShowEditor(true);
          },
          icon: faPlus,
          variant: "primary",
        }}
      />

      <AdminCard padding="none">
        {loading ? (
          <AdminLoadingState message="Loading contact cards..." />
        ) : cards.length === 0 ? (
          <div className="p-6">
            <AdminEmptyState
              title="No contact cards yet"
              description="Add your first contact card to display contact information on your site"
              icon={faAddressCard}
              action={{
                label: "Add card",
                onClick: () => {
                  setEditingId(null);
                  setFormData(emptyCard);
                  setShowEditor(true);
                },
              }}
            />
          </div>
        ) : (
          <AdminDataTable
            items={cards}
            rowKey={(c) => c.id!}
            columns={[
              {
                key: "name",
                header: "Name",
                render: (c) => (
                  <span className="font-medium text-slate-100">{c.name}</span>
                ),
              },
              {
                key: "phone",
                header: "Phone",
                render: (c) => (
                  <a
                    href={`tel:${c.phone}`}
                    className="text-slate-300 hover:text-indigo-300"
                  >
                    {c.phone}
                  </a>
                ),
              },
              {
                key: "email",
                header: "Email",
                render: (c) => (
                  <a
                    href={`mailto:${c.email}`}
                    className="text-slate-300 hover:text-indigo-300"
                  >
                    {c.email}
                  </a>
                ),
              },
            ]}
            actions={(c) => (
              <AdminEditDeleteButtons
                onEdit={() => startEdit(c)}
                onDelete={() => setDeleteConfirm({ isOpen: true, id: c.id! })}
              />
            )}
          />
        )}
      </AdminCard>

      <AdminFormModal
        isOpen={showEditor}
        onClose={resetForm}
        title={editingId ? "Edit contact card" : "Add new contact card"}
        onSubmit={handleSubmit}
        isLoading={isSaving}
        submitLabel={editingId ? "Save changes" : "Add card"}
      >
        <AdminInput
          label="Name"
          type="text"
          value={formData.name}
          onChange={(e) => setFormData({ ...formData, name: e.target.value })}
          required
        />
        <AdminInput
          label="Phone"
          type="tel"
          value={formData.phone}
          onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
          required
        />
        <AdminInput
          label="Email"
          type="email"
          value={formData.email}
          onChange={(e) => setFormData({ ...formData, email: e.target.value })}
          required
        />
      </AdminFormModal>
    </>
  );
}
