"use client";

import {
  faMagnifyingGlass,
  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 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 AdminTextarea from "@/components/admin/AdminTextarea";
import AdminSelect from "@/components/admin/AdminSelect";
import AdminButton from "@/components/admin/AdminButton";
import AdminEmptyState from "@/components/admin/AdminEmptyState";
import AdminConfirmDialog from "@/components/admin/AdminConfirmDialog";
import AdminLoadingState from "@/components/admin/AdminLoadingState";
import AdminBadge from "@/components/admin/AdminBadge";
import { adminClassNames } from "@/components/admin/design-system";
import { adminFetch } from "@/lib/adminFetch";

interface SEOState {
  id?: number;
  pageType: "PROJECT" | "BOLD" | "SERVICE" | "HOME" | "ABOUT" | "CONTACT";
  pageId?: number;
  title: string;
  metaDescription: string;
  keywords?: string;
  ogTitle?: string;
  ogDescription?: string;
  ogImage?: string;
  twitterCard?: string;
  canonicalUrl?: string;
  structuredData?: any;
  robotsMeta: string;
  updatedAt?: Date;
}

const STATIC_PAGE_TYPES = ["HOME", "ABOUT", "CONTACT"];

type PageTypeVariant = "success" | "warning" | "danger" | "info" | "neutral" | "accent";

const PAGE_TYPE_VARIANTS: Record<string, PageTypeVariant> = {
  HOME: "accent",
  ABOUT: "info",
  CONTACT: "info",
  PROJECT: "success",
  BOLD: "warning",
  SERVICE: "neutral",
};

export default function AdminSEO() {
  const [seoEntries, setSeoEntries] = useState<SEOState[]>([]);
  const [selectedEntry, setSelectedEntry] = useState<SEOState | null>(null);
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedType, setSelectedType] = useState<string>("ALL");
  const [loading, setLoading] = useState(true);
  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) => {
      if (selectedEntry) {
        setSelectedEntry({ ...selectedEntry, ogImage: url });
      }
    },
    onDeleteSuccess: () => {
      if (selectedEntry) {
        setSelectedEntry({ ...selectedEntry, ogImage: undefined });
      }
    },
  });

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

  const fetchSEOEntries = async () => {
    try {
      const response = await fetch("/api/seo");
      const data = await response.json();
      setSeoEntries(data);
    } catch {
      showError("Failed to fetch SEO entries");
    } finally {
      setLoading(false);
    }
  };

  const handleImageUpload = async (file: File | File[]) => {
    if (selectedEntry) {
      await uploadImage(file);
    }
  };

  const handleImageDelete = async () => {
    if (selectedEntry?.ogImage) {
      await deleteImage(selectedEntry.ogImage);
    }
  };

  const createNewEntry = () => {
    setSelectedEntry({
      pageType: "HOME",
      pageId: undefined,
      title: "",
      metaDescription: "",
      robotsMeta: "index,follow",
    });
  };

  const saveSEOEntry = async () => {
    if (!selectedEntry) return;

    const entryToSave = {
      ...selectedEntry,
      pageId: STATIC_PAGE_TYPES.includes(selectedEntry.pageType)
        ? undefined
        : selectedEntry.pageId,
    };

    try {
      const response = await adminFetch("/api/seo", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(entryToSave),
      });

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

      showSuccess("SEO entry saved successfully!");
      fetchSEOEntries();
    } catch {
      showError("Failed to save SEO entry");
    }
  };

  const handleDelete = async (id: number) => {
    try {
      const response = await adminFetch(`/api/seo?id=${id}`, { method: "DELETE" });

      if (!response.ok) throw new Error("Failed to delete SEO entry");

      showSuccess("SEO entry deleted successfully!");
      fetchSEOEntries();
      if (selectedEntry?.id === id) {
        setSelectedEntry(null);
      }
    } catch {
      showError("Failed to delete SEO entry");
    } finally {
      setDeleteConfirm({ isOpen: false, id: null });
    }
  };

  const filteredEntries = seoEntries.filter((entry) => {
    const matchesSearch =
      entry.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      entry.metaDescription.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesType = selectedType === "ALL" || entry.pageType === selectedType;
    return matchesSearch && matchesType;
  });

  const groupedEntries = filteredEntries.reduce(
    (acc, entry) => {
      if (!acc[entry.pageType]) acc[entry.pageType] = [];
      acc[entry.pageType].push(entry);
      return acc;
    },
    {} as Record<string, SEOState[]>,
  );

  if (loading) {
    return (
      <>
        <AdminPageHeader title="SEO" description="Manage SEO metadata for every page" />
        <AdminLoadingState message="Loading SEO entries..." />
      </>
    );
  }

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

      <AdminPageHeader
        title="SEO"
        description="Manage search engine and social-media metadata across all pages"
        action={{
          label: "New entry",
          onClick: createNewEntry,
          icon: faPlus,
          variant: "primary" as const,
        }}
      />

      <AdminCard className="mb-6">
        <div className="flex flex-col gap-3 md:flex-row">
          <AdminInput
            placeholder="Search SEO entries..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            leftIcon={<FontAwesomeIcon icon={faMagnifyingGlass} className="h-4 w-4" />}
            className="flex-1"
          />
          <AdminSelect
            options={[
              { value: "ALL", label: "All types" },
              { value: "HOME", label: "Home" },
              { value: "ABOUT", label: "About" },
              { value: "CONTACT", label: "Contact" },
              { value: "PROJECT", label: "Project" },
              { value: "BOLD", label: "Bold" },
              { value: "SERVICE", label: "Service" },
            ]}
            value={selectedType}
            onChange={(e) => setSelectedType(e.target.value)}
            className="w-full md:w-48"
          />
        </div>
      </AdminCard>

      <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
        <div className="space-y-4 lg:col-span-1">
          {Object.keys(groupedEntries).length === 0 ? (
            <AdminCard>
              <AdminEmptyState
                title="No SEO entries"
                description="Create your first SEO entry to get started"
                icon={faMagnifyingGlass}
                action={{ label: "New entry", onClick: createNewEntry }}
              />
            </AdminCard>
          ) : (
            Object.entries(groupedEntries).map(([pageType, entries]) => (
              <AdminCard key={pageType} padding="none">
                <div className="flex items-center justify-between border-b border-slate-800 px-4 py-3">
                  <div className="flex items-center gap-2">
                    <AdminBadge
                      variant={PAGE_TYPE_VARIANTS[pageType] || "neutral"}
                    >
                      {pageType}
                    </AdminBadge>
                    <span className="text-xs text-slate-500">
                      {entries.length} {entries.length === 1 ? "entry" : "entries"}
                    </span>
                  </div>
                </div>
                <ul className="divide-y divide-slate-800">
                  {entries.map((entry) => {
                    const isSelected = selectedEntry?.id === entry.id;
                    return (
                      <li
                        key={entry.id}
                        className={`group relative cursor-pointer px-4 py-3 transition-colors ${
                          isSelected
                            ? "bg-indigo-500/10"
                            : "hover:bg-slate-800/40"
                        }`}
                        onClick={() => setSelectedEntry(entry)}
                      >
                        {isSelected && (
                          <span className="absolute inset-y-0 left-0 w-0.5 bg-indigo-500" />
                        )}
                        <div className="flex items-start justify-between gap-3">
                          <div className="min-w-0 flex-1">
                            <h3 className="mb-0.5 truncate text-sm font-medium text-slate-100">
                              {entry.title || "Untitled"}
                            </h3>
                            <p className="line-clamp-2 text-xs text-slate-400">
                              {entry.metaDescription}
                            </p>
                            {entry.updatedAt && (
                              <div className="mt-1.5 text-[10px] uppercase tracking-wider text-slate-500">
                                Updated{" "}
                                {new Date(entry.updatedAt).toLocaleDateString()}
                              </div>
                            )}
                          </div>
                          <button
                            type="button"
                            onClick={(e) => {
                              e.stopPropagation();
                              setDeleteConfirm({ isOpen: true, id: entry.id! });
                            }}
                            className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-slate-500 transition-colors hover:bg-rose-500/10 hover:text-rose-400"
                            title="Delete"
                            aria-label="Delete"
                          >
                            <FontAwesomeIcon icon={faTrash} className="h-3 w-3" />
                          </button>
                        </div>
                      </li>
                    );
                  })}
                </ul>
              </AdminCard>
            ))
          )}
        </div>

        <div className="lg:col-span-2">
          {selectedEntry ? (
            <AdminCard>
              <AdminForm onSubmit={(e) => e.preventDefault()}>
                <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
                  <AdminSection title="Basic SEO">
                    <AdminSelect
                      label="Page type"
                      options={[
                        { value: "HOME", label: "Home" },
                        { value: "ABOUT", label: "About" },
                        { value: "CONTACT", label: "Contact" },
                        { value: "PROJECT", label: "Project" },
                        { value: "BOLD", label: "Bold" },
                        { value: "SERVICE", label: "Service" },
                      ]}
                      value={selectedEntry.pageType}
                      onChange={(e) =>
                        setSelectedEntry({
                          ...selectedEntry,
                          pageType: e.target.value as SEOState["pageType"],
                        })
                      }
                    />
                    <AdminInput
                      label="Title"
                      value={selectedEntry.title}
                      onChange={(e) =>
                        setSelectedEntry({ ...selectedEntry, title: e.target.value })
                      }
                      maxLength={60}
                      helperText={`${selectedEntry.title.length}/60 characters`}
                    />
                    <AdminTextarea
                      label="Meta description"
                      value={selectedEntry.metaDescription}
                      onChange={(e) =>
                        setSelectedEntry({
                          ...selectedEntry,
                          metaDescription: e.target.value,
                        })
                      }
                      rows={4}
                    />
                    <AdminInput
                      label="Keywords"
                      placeholder="Comma-separated keywords"
                      value={selectedEntry.keywords || ""}
                      onChange={(e) =>
                        setSelectedEntry({
                          ...selectedEntry,
                          keywords: e.target.value,
                        })
                      }
                    />
                  </AdminSection>

                  <AdminSection title="Social media">
                    <AdminInput
                      label="OG title"
                      value={selectedEntry.ogTitle || ""}
                      onChange={(e) =>
                        setSelectedEntry({ ...selectedEntry, ogTitle: e.target.value })
                      }
                      maxLength={95}
                      helperText={`${selectedEntry.ogTitle?.length || 0}/95 characters`}
                    />
                    <AdminTextarea
                      label="OG description"
                      value={selectedEntry.ogDescription || ""}
                      onChange={(e) =>
                        setSelectedEntry({
                          ...selectedEntry,
                          ogDescription: e.target.value,
                        })
                      }
                      rows={3}
                    />
                    <div>
                      <label className={adminClassNames.fieldLabel}>OG image</label>
                      <ImageUpload
                        onImageUpload={handleImageUpload}
                        onImageDelete={handleImageDelete}
                        currentImage={selectedEntry.ogImage}
                        disabled={isUploading}
                        className="w-full"
                      />
                    </div>
                    <AdminInput
                      label="Twitter card"
                      value={selectedEntry.twitterCard || ""}
                      onChange={(e) =>
                        setSelectedEntry({
                          ...selectedEntry,
                          twitterCard: e.target.value,
                        })
                      }
                      maxLength={70}
                      helperText={`${selectedEntry.twitterCard?.length || 0}/70 characters`}
                    />
                  </AdminSection>
                </div>

                <AdminSection title="Advanced">
                  <AdminInput
                    label="Canonical URL"
                    placeholder="https://example.com/page"
                    value={selectedEntry.canonicalUrl || ""}
                    onChange={(e) =>
                      setSelectedEntry({
                        ...selectedEntry,
                        canonicalUrl: e.target.value,
                      })
                    }
                  />
                  <AdminInput
                    label="Robots meta"
                    placeholder="index,follow"
                    value={selectedEntry.robotsMeta}
                    onChange={(e) =>
                      setSelectedEntry({
                        ...selectedEntry,
                        robotsMeta: e.target.value,
                      })
                    }
                    helperText="Common values: index,follow, noindex,nofollow"
                  />
                </AdminSection>

                <div className="-mx-6 -mb-6 mt-8 flex justify-end gap-3 border-t border-slate-800 bg-slate-900/50 px-6 py-4">
                  <AdminButton variant="secondary" onClick={() => setSelectedEntry(null)}>
                    Cancel
                  </AdminButton>
                  <AdminButton variant="primary" onClick={saveSEOEntry}>
                    Save changes
                  </AdminButton>
                </div>
              </AdminForm>
            </AdminCard>
          ) : (
            <AdminCard>
              <AdminEmptyState
                title="No entry selected"
                description="Select an SEO entry from the list or create a new one"
                icon={faMagnifyingGlass}
                action={{ label: "Create entry", onClick: createNewEntry }}
              />
            </AdminCard>
          )}
        </div>
      </div>
    </>
  );
}
