"use client";

import {
  faArrowDown,
  faArrowUp,
  faBars,
  faPlus,
  faSave,
  faTrash,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useEffect, useState } from "react";
import { v4 as uuidv4 } from "uuid";
import Toast from "@/components/ui/Toast";
import { useAdminToast } from "@/hooks/admin/useAdminToast";
import AdminPageHeader from "@/components/admin/AdminPageHeader";
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 AdminSelect from "@/components/admin/AdminSelect";
import AdminButton from "@/components/admin/AdminButton";
import AdminEmptyState from "@/components/admin/AdminEmptyState";
import AdminLoadingState from "@/components/admin/AdminLoadingState";
import { adminFetch } from "@/lib/adminFetch";

interface LinkType {
  id: string;
  label: string;
  url: string;
  newTab: boolean;
  order: number;
  isScrollLink: boolean;
}

interface NavbarType {
  branding: string;
  links: LinkType[];
}

export default function AdminNavbar() {
  const [navbar, setNavbar] = useState<NavbarType>({ branding: "Nitescape", links: [] });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const { toast, showSuccess, showError, hideToast } = useAdminToast();

  useEffect(() => {
    let cancelled = false;
    fetch("/api/navbar")
      .then((res) => res.json())
      .then((data) => {
        if (cancelled) return;
        if (data && data.links) {
          const links: LinkType[] = data.links.map((link: any, i: number) => ({
            ...link,
            id: link.id || uuidv4(),
            order: link.order ?? i,
            isScrollLink: link.isScrollLink ?? link.url.startsWith("#"),
          }));
          setNavbar({ ...data, links });
        } else {
          setNavbar({ branding: "Nitescape", links: [] });
        }
        setLoading(false);
      })
      .catch(() => {
        if (!cancelled) {
          showError("Failed to load navbar settings");
          setLoading(false);
        }
      });
    return () => {
      cancelled = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const moveLink = (index: number, direction: number) => {
    const newLinks = [...navbar.links];
    const target = index + direction;
    if (target < 0 || target >= newLinks.length) return;
    [newLinks[index], newLinks[target]] = [newLinks[target], newLinks[index]];
    const ordered = newLinks.map((l, i) => ({ ...l, order: i }));
    setNavbar({ ...navbar, links: ordered });
  };

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    try {
      const linksWithId: LinkType[] = navbar.links.map((link, i) => ({
        ...link,
        id: link.id || uuidv4(),
        order: link.order ?? i,
        isScrollLink: link.isScrollLink ?? link.url.startsWith("#"),
      }));

      const response = await adminFetch("/api/navbar", {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ ...navbar, links: linksWithId }),
      });

      if (!response.ok) throw new Error("Failed to save navbar");

      showSuccess("Navbar settings saved successfully!");
    } catch {
      showError("Failed to save navbar settings. Please try again.");
    } finally {
      setSaving(false);
    }
  };

  const addLink = () => {
    const maxOrder =
      navbar.links.length > 0 ? Math.max(...navbar.links.map((l) => l.order ?? 0)) : 0;
    const newLink: LinkType = {
      id: uuidv4(),
      label: "New Link",
      url: "",
      newTab: false,
      order: maxOrder + 1,
      isScrollLink: false,
    };
    setNavbar({ ...navbar, links: [...navbar.links, newLink] });
  };

  const removeLink = (index: number) => {
    const updatedLinks = navbar.links.filter((_, i) => i !== index);
    setNavbar({ ...navbar, links: updatedLinks });
  };

  if (loading) {
    return (
      <>
        <AdminPageHeader title="Navbar" description="Manage navigation bar settings" />
        <AdminLoadingState message="Loading navbar..." />
      </>
    );
  }

  return (
    <>
      {toast && <Toast message={toast.message} type={toast.type} onClose={hideToast} />}
      <AdminPageHeader
        title="Navbar"
        description="Manage your website navigation bar branding and links"
      />

      <AdminCard>
        <AdminForm onSubmit={handleSave}>
          <AdminSection title="Branding">
            <AdminInput
              label="Brand name"
              placeholder="Nitescape"
              value={navbar.branding}
              onChange={(e) => setNavbar({ ...navbar, branding: e.target.value })}
              required
            />
          </AdminSection>

          <AdminSection
            title="Navigation links"
            description="Links that appear in the public site navigation bar"
            action={
              navbar.links.length > 0 ? (
                <AdminButton
                  type="button"
                  variant="secondary"
                  size="sm"
                  onClick={addLink}
                  icon={faPlus}
                >
                  Add link
                </AdminButton>
              ) : undefined
            }
          >
            {navbar.links.length === 0 ? (
              <AdminEmptyState
                title="No links yet"
                description="Add your first navigation link"
                icon={faBars}
                action={{ label: "Add link", onClick: addLink }}
              />
            ) : (
              <div className="space-y-2">
                {navbar.links.map((link, index) => (
                  <div
                    key={link.id}
                    className="flex flex-col gap-3 rounded-lg border border-slate-800 bg-slate-950 p-3 lg:flex-row lg:items-center"
                  >
                    <div className="flex items-center gap-1">
                      <button
                        type="button"
                        onClick={() => moveLink(index, -1)}
                        disabled={index === 0}
                        className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-400 transition-colors hover:bg-slate-800 hover:text-slate-100 disabled:cursor-not-allowed disabled:opacity-30"
                        title="Move up"
                        aria-label="Move up"
                      >
                        <FontAwesomeIcon icon={faArrowUp} className="h-3 w-3" />
                      </button>
                      <button
                        type="button"
                        onClick={() => moveLink(index, 1)}
                        disabled={index === navbar.links.length - 1}
                        className="inline-flex h-7 w-7 items-center justify-center rounded-md text-slate-400 transition-colors hover:bg-slate-800 hover:text-slate-100 disabled:cursor-not-allowed disabled:opacity-30"
                        title="Move down"
                        aria-label="Move down"
                      >
                        <FontAwesomeIcon icon={faArrowDown} className="h-3 w-3" />
                      </button>
                      <span className="ml-1 w-5 text-center text-xs text-slate-500">
                        {index + 1}
                      </span>
                    </div>
                    <div className="grid flex-1 grid-cols-1 gap-2 md:grid-cols-2">
                      <AdminInput
                        placeholder="Label"
                        value={link.label}
                        onChange={(e) => {
                          const updatedLinks = [...navbar.links];
                          updatedLinks[index].label = e.target.value;
                          setNavbar({ ...navbar, links: updatedLinks });
                        }}
                      />
                      <AdminInput
                        placeholder="URL or #section"
                        value={link.url}
                        onChange={(e) => {
                          const updatedLinks = [...navbar.links];
                          updatedLinks[index].url = e.target.value;
                          setNavbar({ ...navbar, links: updatedLinks });
                        }}
                      />
                    </div>
                    <div className="flex items-center gap-2">
                      <AdminSelect
                        options={[
                          { value: "no", label: "Same tab" },
                          { value: "yes", label: "New tab" },
                        ]}
                        value={link.newTab ? "yes" : "no"}
                        onChange={(e) => {
                          const updatedLinks = [...navbar.links];
                          updatedLinks[index].newTab = e.target.value === "yes";
                          setNavbar({ ...navbar, links: updatedLinks });
                        }}
                        className="w-32"
                      />
                      <AdminSelect
                        options={[
                          { value: "no", label: "Regular" },
                          { value: "yes", label: "Scroll" },
                        ]}
                        value={link.isScrollLink ? "yes" : "no"}
                        onChange={(e) => {
                          const updatedLinks = [...navbar.links];
                          updatedLinks[index].isScrollLink = e.target.value === "yes";
                          setNavbar({ ...navbar, links: updatedLinks });
                        }}
                        className="w-32"
                      />
                      <button
                        type="button"
                        onClick={() => removeLink(index)}
                        className="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-md text-slate-400 transition-colors hover:bg-rose-500/10 hover:text-rose-400"
                        title="Remove link"
                        aria-label="Remove link"
                      >
                        <FontAwesomeIcon icon={faTrash} />
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </AdminSection>

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