"use client";

import {
  faArrowLeft,
  faCog,
  faEye,
  faFileText,
  faSave,
  faShare,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import InfoTooltip from "@/components/ui/InfoTooltip";
import Toast, { useToast } from "@/components/ui/Toast";
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 AdminLoadingState from "@/components/admin/AdminLoadingState";
import { adminFetch } from "@/lib/adminFetch";
import AdminErrorState from "@/components/admin/AdminErrorState";
import AdminBadge from "@/components/admin/AdminBadge";
import { adminClassNames } from "@/components/admin/design-system";

type PageType = "PROJECT" | "BOLD" | "SERVICE" | "HOME" | "ABOUT" | "CONTACT";

interface SEOMetadata {
  id: number;
  pageType: PageType;
  pageId: number | null;
  title: string;
  metaDescription: string;
  keywords: string | null;
  ogTitle: string | null;
  ogDescription: string | null;
  ogImage: string | null;
  twitterCard: string | null;
  canonicalUrl: string | null;
  robotsMeta: string | null;
}

interface EditSEOFormProps {
  type: string;
  id: string;
}

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

export default function EditSEOForm({ type, id }: EditSEOFormProps) {
  const router = useRouter();
  const [metadata, setMetadata] = useState<SEOMetadata | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const { toast, showToast, hideToast } = useToast();

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

  const fetchMetadata = async () => {
    try {
      const response = await fetch(`/api/seo/${id}`);
      const data = await response.json();
      setMetadata(data);
    } catch (error) {
      console.error("Error fetching SEO metadata:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!metadata) return;

    setSaving(true);
    try {
      const response = await adminFetch(`/api/seo/${id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(metadata),
      });

      if (response.ok) {
        router.push("/admin/seo");
        showToast("SEO entry updated successfully!", "success");
      } else {
        throw new Error("Failed to update SEO metadata");
      }
    } catch (error) {
      console.error("Error updating SEO metadata:", error);
      showToast("Failed to update SEO entry. Please try again.", "error");
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <>
        <AdminPageHeader title="Edit SEO" description="Edit SEO metadata" />
        <AdminLoadingState message="Loading SEO metadata..." />
      </>
    );
  }

  if (!metadata) {
    return (
      <>
        <AdminPageHeader title="Edit SEO" description="Edit SEO metadata" />
        <AdminErrorState
          title="Not found"
          message="SEO metadata for this page could not be loaded."
        />
      </>
    );
  }

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

      <div className="mb-4">
        <button
          type="button"
          onClick={() => router.push("/admin/seo")}
          className="inline-flex items-center gap-2 text-sm text-slate-400 transition-colors hover:text-slate-100"
        >
          <FontAwesomeIcon icon={faArrowLeft} className="h-3.5 w-3.5" />
          Back to SEO
        </button>
      </div>

      <AdminPageHeader
        title="Edit SEO metadata"
        description="Optimize search engine visibility and social media sharing for this page"
      />

      <div className="mb-6 flex items-center gap-2">
        <span className={adminClassNames.sectionLabel}>Page</span>
        <AdminBadge variant={PAGE_TYPE_VARIANTS[type.toUpperCase()] || "neutral"}>
          {type.toUpperCase()}
        </AdminBadge>
      </div>

      <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
        <div className="space-y-6 lg:col-span-2">
          <AdminForm onSubmit={handleSubmit}>
            <AdminCard>
              <AdminSection
                title={
                  <span className="inline-flex items-center gap-2">
                    <FontAwesomeIcon icon={faFileText} className="h-3.5 w-3.5" />
                    Basic meta tags
                  </span>
                }
              >
                <AdminInput
                  label={
                    <span className="inline-flex items-center gap-1">
                      Title
                      <InfoTooltip tip="The page title appears in the browser tab and search results. Keep it under 60 characters.">
                        i
                      </InfoTooltip>
                    </span>
                  }
                  value={metadata.title}
                  onChange={(e) => setMetadata({ ...metadata, title: e.target.value })}
                  maxLength={60}
                  required
                  helperText={`${metadata.title.length}/60 characters`}
                />
                <AdminTextarea
                  label={
                    <span className="inline-flex items-center gap-1">
                      Meta description
                      <InfoTooltip tip="The meta description appears in search results. 150-160 characters is ideal.">
                        i
                      </InfoTooltip>
                    </span>
                  }
                  value={metadata.metaDescription}
                  onChange={(e) =>
                    setMetadata({ ...metadata, metaDescription: e.target.value })
                  }
                  rows={3}
                  required
                  helperText={`${metadata.metaDescription.length}/160 characters`}
                />
                <AdminInput
                  label={
                    <span className="inline-flex items-center gap-1">
                      Keywords
                      <InfoTooltip tip="Comma-separated keywords relevant to this page.">
                        i
                      </InfoTooltip>
                    </span>
                  }
                  value={metadata.keywords || ""}
                  onChange={(e) => setMetadata({ ...metadata, keywords: e.target.value })}
                  placeholder="Comma-separated keywords"
                />
              </AdminSection>
            </AdminCard>

            <AdminCard>
              <AdminSection
                title={
                  <span className="inline-flex items-center gap-2">
                    <FontAwesomeIcon icon={faShare} className="h-3.5 w-3.5" />
                    Social media
                  </span>
                }
              >
                <AdminInput
                  label={
                    <span className="inline-flex items-center gap-1">
                      OG title
                      <InfoTooltip tip="Title shown when the page is shared on social media.">
                        i
                      </InfoTooltip>
                    </span>
                  }
                  value={metadata.ogTitle || ""}
                  onChange={(e) => setMetadata({ ...metadata, ogTitle: e.target.value })}
                  maxLength={95}
                />
                <AdminTextarea
                  label={
                    <span className="inline-flex items-center gap-1">
                      OG description
                      <InfoTooltip tip="Description shown when the page is shared on social media.">
                        i
                      </InfoTooltip>
                    </span>
                  }
                  value={metadata.ogDescription || ""}
                  onChange={(e) =>
                    setMetadata({ ...metadata, ogDescription: e.target.value })
                  }
                  rows={3}
                />
                <AdminInput
                  label={
                    <span className="inline-flex items-center gap-1">
                      OG image URL
                      <InfoTooltip tip="Full URL to an image (1200x630px recommended).">
                        i
                      </InfoTooltip>
                    </span>
                  }
                  type="url"
                  value={metadata.ogImage || ""}
                  onChange={(e) => setMetadata({ ...metadata, ogImage: e.target.value })}
                />
                <AdminSelect
                  label={
                    <span className="inline-flex items-center gap-1">
                      Twitter card type
                      <InfoTooltip tip="Choose how the page appears on Twitter.">
                        i
                      </InfoTooltip>
                    </span>
                  }
                  options={[
                    { value: "", label: "Select a card type" },
                    { value: "summary", label: "Summary" },
                    { value: "summary_large_image", label: "Summary large image" },
                  ]}
                  value={metadata.twitterCard || ""}
                  onChange={(e) =>
                    setMetadata({ ...metadata, twitterCard: e.target.value })
                  }
                />
              </AdminSection>
            </AdminCard>

            <AdminCard>
              <AdminSection
                title={
                  <span className="inline-flex items-center gap-2">
                    <FontAwesomeIcon icon={faCog} className="h-3.5 w-3.5" />
                    Advanced settings
                  </span>
                }
              >
                <AdminInput
                  label={
                    <span className="inline-flex items-center gap-1">
                      Canonical URL
                      <InfoTooltip tip="The preferred URL for this page, avoids duplicate-content issues.">
                        i
                      </InfoTooltip>
                    </span>
                  }
                  type="url"
                  value={metadata.canonicalUrl || ""}
                  onChange={(e) =>
                    setMetadata({ ...metadata, canonicalUrl: e.target.value })
                  }
                />
                <AdminSelect
                  label={
                    <span className="inline-flex items-center gap-1">
                      Robots meta
                      <InfoTooltip tip="Controls if search engines index this page and follow its links.">
                        i
                      </InfoTooltip>
                    </span>
                  }
                  options={[
                    { value: "index,follow", label: "Index, Follow" },
                    { value: "noindex,follow", label: "No index, Follow" },
                    { value: "index,nofollow", label: "Index, No follow" },
                    { value: "noindex,nofollow", label: "No index, No follow" },
                  ]}
                  value={metadata.robotsMeta || "index,follow"}
                  onChange={(e) =>
                    setMetadata({ ...metadata, robotsMeta: e.target.value })
                  }
                />
              </AdminSection>
            </AdminCard>

            <div className="flex justify-end gap-3">
              <AdminButton
                type="button"
                variant="secondary"
                onClick={() => router.push("/admin/seo")}
              >
                Cancel
              </AdminButton>
              <AdminButton
                type="submit"
                variant="primary"
                isLoading={saving}
                icon={faSave}
              >
                Save changes
              </AdminButton>
            </div>
          </AdminForm>
        </div>

        <div className="lg:sticky lg:top-8 lg:self-start">
          <AdminCard>
            <AdminSection
              title={
                <span className="inline-flex items-center gap-2">
                  <FontAwesomeIcon icon={faEye} className="h-3.5 w-3.5" />
                  Live preview
                </span>
              }
            >
              <div>
                <h3 className={`${adminClassNames.sectionLabel} mb-2`}>Google search</h3>
                <div className="rounded-lg border border-slate-800 bg-slate-950 p-4">
                  <div className="truncate text-xs text-emerald-400">
                    {metadata.canonicalUrl || "example.com"}
                  </div>
                  <div className="mt-1 text-base font-medium text-sky-300">
                    {metadata.title}
                  </div>
                  <div className="mt-1 text-sm text-slate-400">
                    {metadata.metaDescription}
                  </div>
                </div>
              </div>

              <div>
                <h3 className={`${adminClassNames.sectionLabel} mb-2`}>Social card</h3>
                <div className="overflow-hidden rounded-lg border border-slate-800 bg-slate-950">
                  {metadata.ogImage && (
                    <Image
                      src={metadata.ogImage}
                      alt="Social media preview"
                      width={600}
                      height={200}
                      className="h-32 w-full object-cover"
                      style={{ objectFit: "cover" }}
                      unoptimized={
                        metadata.ogImage.startsWith("http") &&
                        !metadata.ogImage.startsWith(
                          process.env.NEXT_PUBLIC_BASE_URL || "",
                        )
                      }
                    />
                  )}
                  <div className="p-4">
                    <div className="text-sm font-semibold text-slate-100">
                      {metadata.ogTitle || metadata.title}
                    </div>
                    <div className="mt-1 text-xs text-slate-400">
                      {metadata.ogDescription || metadata.metaDescription}
                    </div>
                  </div>
                </div>
              </div>
            </AdminSection>
          </AdminCard>
        </div>
      </div>
    </>
  );
}
