"use client";

import { faPlus, faFolder } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useEffect, useState } from "react";
import IconPicker from "@/components/IconPicker";
import Toast from "@/components/ui/Toast";
import { useAdminToast } from "@/hooks/admin/useAdminToast";
import { getIcon } from "@/lib/icons";
import type { Service, ServicesCTA } from "@/types/models";
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 AdminEmptyState from "@/components/admin/AdminEmptyState";
import AdminConfirmDialog from "@/components/admin/AdminConfirmDialog";
import AdminFormModal from "@/components/admin/AdminFormModal";
import AdminEditDeleteButtons from "@/components/admin/AdminEditDeleteButtons";
import AdminLoadingState from "@/components/admin/AdminLoadingState";
import { adminFetch } from "@/lib/adminFetch";

export default function ServicesTab() {
  const [services, setServices] = useState<Service[]>([]);
  const [newService, setNewService] = useState<Service>({
    title: "",
    description: "",
    icon: "Lightbulb",
  });
  const [editingId, setEditingId] = useState<number | null>(null);
  const [ctaSettings, setCtaSettings] = useState<ServicesCTA>({
    buttonText: "Get Started",
    buttonLink: "/contact",
  });
  const [savingCta, setSavingCta] = useState(false);
  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();

  useEffect(() => {
    let cancelled = false;
    Promise.all([fetch("/api/services"), fetch("/api/services-cta")])
      .then(async ([sRes, cRes]) => {
        if (cancelled) return;
        setServices(await sRes.json());
        const ctaData = await cRes.json();
        setCtaSettings(ctaData || { buttonText: "Get Started", buttonLink: "/contact" });
        setLoading(false);
      })
      .catch(() => {
        if (!cancelled) {
          showError("Failed to load services");
          setLoading(false);
        }
      });
    return () => {
      cancelled = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

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

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

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

  const handleSaveCTA = async () => {
    setSavingCta(true);
    try {
      const response = await adminFetch("/api/services-cta", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(ctaSettings),
      });
      if (!response.ok) throw new Error();
      showSuccess("CTA settings saved successfully!");
    } catch {
      showError("Failed to save CTA settings.");
    } finally {
      setSavingCta(false);
    }
  };

  const startEdit = (service: Service) => {
    setNewService({ ...service });
    setEditingId(service.id!);
    setShowEditor(true);
  };

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

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

      <div className="space-y-6">
        <AdminCard>
          <AdminForm onSubmit={(e) => e.preventDefault()}>
            <AdminSection title="Call-to-action button">
              <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                <AdminInput
                  label="Button text"
                  placeholder="Get Started"
                  value={ctaSettings.buttonText}
                  onChange={(e) =>
                    setCtaSettings({ ...ctaSettings, buttonText: e.target.value })
                  }
                />
                <AdminInput
                  label="Button link"
                  placeholder="/contact"
                  value={ctaSettings.buttonLink}
                  onChange={(e) =>
                    setCtaSettings({ ...ctaSettings, buttonLink: e.target.value })
                  }
                />
              </div>
            </AdminSection>
            <div className="-mx-6 -mb-6 mt-6 flex justify-end border-t border-slate-800 px-6 py-4">
              <AdminButton variant="primary" onClick={handleSaveCTA} isLoading={savingCta}>
                Save CTA settings
              </AdminButton>
            </div>
          </AdminForm>
        </AdminCard>

        <AdminCard
          header={
            <div className="flex items-center justify-between">
              <div>
                <h3 className="text-sm font-semibold text-slate-100">Services</h3>
                <p className="text-xs text-slate-400">Manage services displayed on the homepage</p>
              </div>
              <AdminButton
                variant="primary"
                size="sm"
                icon={faPlus}
                onClick={() => {
                  setEditingId(null);
                  setNewService({ title: "", description: "", icon: "Lightbulb" });
                  setShowEditor(true);
                }}
              >
                Add service
              </AdminButton>
            </div>
          }
          padding="none"
        >
          {services.length === 0 ? (
            <div className="p-6">
              <AdminEmptyState
                title="No services yet"
                description="Create your first service to get started"
                icon={faFolder}
                action={{ label: "Add service", onClick: () => setShowEditor(true) }}
              />
            </div>
          ) : (
            <ul className="divide-y divide-slate-800">
              {services.map((service) => (
                <li
                  key={service.id}
                  className="flex items-center gap-4 px-6 py-4 transition-colors hover:bg-slate-800/40"
                >
                  <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-indigo-500/10 text-indigo-400">
                    <FontAwesomeIcon icon={getIcon(service.icon)} className="h-4 w-4" />
                  </div>
                  <div className="min-w-0 flex-1">
                    <h4 className="truncate text-sm font-semibold text-slate-100">
                      {service.title}
                    </h4>
                    <p className="truncate text-sm text-slate-400">{service.description}</p>
                  </div>
                  <AdminEditDeleteButtons
                    onEdit={() => startEdit(service)}
                    onDelete={() =>
                      setDeleteConfirm({ isOpen: true, id: service.id! })
                    }
                  />
                </li>
              ))}
            </ul>
          )}
        </AdminCard>
      </div>

      <AdminFormModal
        isOpen={showEditor}
        onClose={resetForm}
        title={editingId ? "Edit service" : "Add new service"}
        onSubmit={handleSubmit}
        submitLabel={editingId ? "Save changes" : "Add service"}
      >
        <AdminInput
          label="Service title"
          placeholder="Enter service title"
          value={newService.title}
          onChange={(e) => setNewService({ ...newService, title: e.target.value })}
          required
        />
        <AdminTextarea
          label="Service description"
          placeholder="Enter service description"
          value={newService.description}
          onChange={(e) => setNewService({ ...newService, description: e.target.value })}
          maxLength={1000}
          showCharacterCount
          rows={4}
        />
        <div>
          <label className="mb-1.5 block text-sm font-medium text-slate-300">
            Service 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(newService.icon)} className="h-5 w-5" />
            </div>
            <div className="flex-1">
              <IconPicker
                value={newService.icon}
                onChange={(icon) => setNewService({ ...newService, icon })}
              />
            </div>
          </div>
        </div>
      </AdminFormModal>
    </>
  );
}
