"use client";

import {
  faPlus,
  faSave,
  faTrash,
  faImage,
  faLightbulb,
  faMobileScreen,
  faCirclePlay,
  faCircleInfo,
  faBullhorn,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { type EmojiClickData, EmojiStyle, Theme } from "emoji-picker-react";
import dynamic from "next/dynamic";
import { useEffect, useRef, useState } from "react";
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 AdminTextarea from "@/components/admin/AdminTextarea";
import AdminButton from "@/components/admin/AdminButton";
import AdminLoadingState from "@/components/admin/AdminLoadingState";
import AdminErrorState from "@/components/admin/AdminErrorState";
import AdminTabNavigation from "@/components/admin/AdminTabNavigation";
import { adminFetch } from "@/lib/adminFetch";

const defaultFeature = { icon: "💡", title: "", description: "" };
const Picker = dynamic(() => import("emoji-picker-react"), { ssr: false });

type Tab = "hero" | "features" | "app-stores" | "tutorial" | "info" | "cta";

const TABS = [
  { id: "hero", label: "Hero", icon: faImage },
  { id: "features", label: "Features", icon: faLightbulb },
  { id: "app-stores", label: "App stores", icon: faMobileScreen },
  { id: "tutorial", label: "Tutorial", icon: faCirclePlay },
  { id: "info", label: "Info", icon: faCircleInfo },
  { id: "cta", label: "CTA", icon: faBullhorn },
] as const;

export default function AdminWattsLights() {
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [activeTab, setActiveTab] = useState<Tab>("hero");
  const [data, setData] = useState<any>(null);
  const [features, setFeatures] = useState<any[]>([]);
  const [iconPickerOpen, setIconPickerOpen] = useState<number | null>(null);
  const iconPickerTriggerRef = useRef<HTMLDivElement>(null);
  const pickerRef = useRef<HTMLDivElement>(null);
  const { toast, showSuccess, showError, hideToast } = useAdminToast();

  useEffect(() => {
    let cancelled = false;
    fetch("/api/watts-lights")
      .then((res) => res.json())
      .then((json) => {
        if (!cancelled) {
          setData(json);
          setFeatures(json.features || []);
          setLoading(false);
        }
      })
      .catch(() => {
        if (!cancelled) {
          showError("Failed to load Watts Lights page data");
          setLoading(false);
        }
      });
    return () => {
      cancelled = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as Node;
      const isClickInsidePicker = pickerRef.current?.contains(target);
      const isClickInsideTrigger = iconPickerTriggerRef.current?.contains(target);
      if (!isClickInsidePicker && !isClickInsideTrigger) {
        setIconPickerOpen(null);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const handleFeatureChange = (idx: number, key: string, value: string) => {
    setFeatures((prev) => prev.map((f, i) => (i === idx ? { ...f, [key]: value } : f)));
  };
  const handleAddFeature = () => setFeatures([...features, { ...defaultFeature }]);
  const handleRemoveFeature = (idx: number) =>
    setFeatures(features.filter((_, i) => i !== idx));

  const handleEmojiClick = (emojiData: EmojiClickData, idx: number) => {
    setFeatures((prev) =>
      prev.map((f, i) => (i === idx ? { ...f, icon: emojiData.emoji } : f)),
    );
    setIconPickerOpen(null);
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      const payload = {
        hero: data.hero,
        features,
        infoSection: data.infoSection,
        ctaSection: data.ctaSection,
        appStores: data.appStores,
        tutorialVideo: data.tutorialVideo,
      };
      const res = await adminFetch("/api/watts-lights", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      if (res.ok) {
        showSuccess("Watts Lights page updated successfully!");
      } else {
        showError("Failed to update. Please try again.");
      }
    } catch {
      showError("Failed to update. Please try again.");
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <>
        <AdminPageHeader
          title="Watts Lights"
          description="Manage the Watts Lights product page content"
        />
        <AdminLoadingState message="Loading page data..." />
      </>
    );
  }

  if (!data) {
    return (
      <>
        <AdminPageHeader
          title="Watts Lights"
          description="Manage the Watts Lights product page content"
        />
        <AdminErrorState
          title="Failed to load"
          message="We couldn't load the Watts Lights page data. Please try again."
        />
      </>
    );
  }

  return (
    <>
      {toast && <Toast message={toast.message} type={toast.type} onClose={hideToast} />}
      <AdminPageHeader
        title="Watts Lights"
        description="Manage all content for the Watts Lights product page"
      />

      <AdminTabNavigation
        tabs={TABS as unknown as { id: string; label: string; icon: any }[]}
        activeTab={activeTab}
        onTabChange={(id) => setActiveTab(id as Tab)}
        className="mb-6"
      />

      <AdminCard>
        <AdminForm onSubmit={(e) => e.preventDefault()}>
          {activeTab === "hero" && (
            <AdminSection
              title="Hero section"
              description="Content shown at the top of the Watts Lights page"
            >
              <AdminInput
                label="Title"
                placeholder="Enter hero title"
                value={data.hero.title}
                onChange={(e) =>
                  setData({ ...data, hero: { ...data.hero, title: e.target.value } })
                }
              />
              <AdminInput
                label="Subtitle"
                placeholder="Enter hero subtitle"
                value={data.hero.subtitle}
                onChange={(e) =>
                  setData({ ...data, hero: { ...data.hero, subtitle: e.target.value } })
                }
              />
              <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                <AdminInput
                  label="Button text"
                  placeholder="Get Started"
                  value={data.hero.buttonText}
                  onChange={(e) =>
                    setData({
                      ...data,
                      hero: { ...data.hero, buttonText: e.target.value },
                    })
                  }
                />
                <AdminInput
                  label="Button link"
                  placeholder="/contact"
                  value={data.hero.buttonLink}
                  onChange={(e) =>
                    setData({
                      ...data,
                      hero: { ...data.hero, buttonLink: e.target.value },
                    })
                  }
                />
              </div>
              <AdminInput
                label="YouTube video ID"
                placeholder="nNJq94Q2Lsw"
                value={data.hero.youtubeVideoId}
                onChange={(e) =>
                  setData({
                    ...data,
                    hero: { ...data.hero, youtubeVideoId: e.target.value },
                  })
                }
                helperText="Enter only the video ID, not the full YouTube URL"
              />
            </AdminSection>
          )}

          {activeTab === "features" && (
            <AdminSection
              title="Features"
              description="Highlight the key features of Watts Lights"
              action={
                <AdminButton
                  type="button"
                  variant="secondary"
                  size="sm"
                  onClick={handleAddFeature}
                  icon={faPlus}
                >
                  Add feature
                </AdminButton>
              }
            >
              {features.length === 0 ? (
                <p className="text-sm text-slate-400">No features added yet.</p>
              ) : (
                <div className="space-y-3">
                  {features.map((feature, idx) => (
                    <div
                      key={idx}
                      className="flex flex-col gap-3 rounded-lg border border-slate-800 bg-slate-950 p-4 md:flex-row md:items-center"
                    >
                      <div ref={iconPickerTriggerRef} className="relative">
                        <button
                          type="button"
                          className="inline-flex h-11 w-11 items-center justify-center rounded-lg border border-slate-800 bg-slate-900 text-2xl transition-colors hover:border-slate-700 hover:bg-slate-800 focus:outline-none focus:ring-2 focus:ring-indigo-500/60"
                          onClick={() =>
                            setIconPickerOpen(iconPickerOpen === idx ? null : idx)
                          }
                          aria-label="Pick icon"
                        >
                          {feature.icon}
                        </button>
                        {iconPickerOpen === idx && (
                          <div ref={pickerRef} className="absolute z-50 mt-2">
                            <Picker
                              onEmojiClick={(emojiData) =>
                                handleEmojiClick(emojiData, idx)
                              }
                              theme={Theme.DARK}
                              width={350}
                              height={400}
                              searchPlaceholder="Search emojis..."
                              emojiStyle={EmojiStyle.NATIVE}
                              autoFocusSearch={false}
                              skinTonesDisabled
                              searchDisabled={false}
                              previewConfig={{ showPreview: false }}
                            />
                          </div>
                        )}
                      </div>
                      <AdminInput
                        placeholder="Feature title"
                        value={feature.title}
                        onChange={(e) =>
                          handleFeatureChange(idx, "title", e.target.value)
                        }
                        className="flex-1"
                      />
                      <AdminInput
                        placeholder="Feature description"
                        value={feature.description}
                        onChange={(e) =>
                          handleFeatureChange(idx, "description", e.target.value)
                        }
                        className="flex-1"
                      />
                      <button
                        type="button"
                        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"
                        onClick={() => handleRemoveFeature(idx)}
                        title="Remove feature"
                        aria-label="Remove feature"
                      >
                        <FontAwesomeIcon icon={faTrash} />
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </AdminSection>
          )}

          {activeTab === "app-stores" && (
            <AdminSection
              title="App stores"
              description="Configure the download links displayed with the app store badges"
            >
              <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                <AdminInput
                  label="Apple App Store link"
                  placeholder="https://apps.apple.com/..."
                  value={data.appStores?.appleStoreLink || ""}
                  onChange={(e) =>
                    setData({
                      ...data,
                      appStores: {
                        ...data.appStores,
                        appleStoreLink: e.target.value,
                      },
                    })
                  }
                />
                <AdminInput
                  label="Google Play Store link"
                  placeholder="https://play.google.com/store/..."
                  value={data.appStores?.googlePlayLink || ""}
                  onChange={(e) =>
                    setData({
                      ...data,
                      appStores: {
                        ...data.appStores,
                        googlePlayLink: e.target.value,
                      },
                    })
                  }
                />
              </div>
            </AdminSection>
          )}

          {activeTab === "tutorial" && (
            <AdminSection title="Tutorial video" description="Embedded walkthrough video">
              <AdminInput
                label="Title"
                placeholder="How to use Watts Lights app"
                value={data.tutorialVideo?.title || ""}
                onChange={(e) =>
                  setData({
                    ...data,
                    tutorialVideo: {
                      ...data.tutorialVideo,
                      title: e.target.value,
                    },
                  })
                }
              />
              <AdminTextarea
                label="Description"
                placeholder="Learn how to control your Watts Lights system..."
                value={data.tutorialVideo?.description || ""}
                onChange={(e) =>
                  setData({
                    ...data,
                    tutorialVideo: {
                      ...data.tutorialVideo,
                      description: e.target.value,
                    },
                  })
                }
                rows={4}
              />
              <AdminInput
                label="YouTube video ID"
                placeholder="dQw4w9WgXcQ"
                value={data.tutorialVideo?.youtubeVideoId || ""}
                onChange={(e) =>
                  setData({
                    ...data,
                    tutorialVideo: {
                      ...data.tutorialVideo,
                      youtubeVideoId: e.target.value,
                    },
                  })
                }
                helperText="Enter only the video ID, not the full YouTube URL"
              />
            </AdminSection>
          )}

          {activeTab === "info" && (
            <AdminSection title="Info section">
              <AdminInput
                label="Title"
                placeholder="About Watts Lights"
                value={data.infoSection.title}
                onChange={(e) =>
                  setData({
                    ...data,
                    infoSection: { ...data.infoSection, title: e.target.value },
                  })
                }
              />
              <AdminTextarea
                label="Content"
                placeholder="Enter information about Watts Lights..."
                value={data.infoSection.content}
                onChange={(e) =>
                  setData({
                    ...data,
                    infoSection: { ...data.infoSection, content: e.target.value },
                  })
                }
                rows={6}
              />
            </AdminSection>
          )}

          {activeTab === "cta" && (
            <AdminSection title="Call-to-action">
              <AdminInput
                label="Headline"
                placeholder="Ready to get started?"
                value={data.ctaSection.headline}
                onChange={(e) =>
                  setData({
                    ...data,
                    ctaSection: { ...data.ctaSection, headline: e.target.value },
                  })
                }
              />
              <AdminInput
                label="Text"
                placeholder="Contact us today..."
                value={data.ctaSection.text}
                onChange={(e) =>
                  setData({
                    ...data,
                    ctaSection: { ...data.ctaSection, text: e.target.value },
                  })
                }
              />
              <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                <AdminInput
                  label="Button text"
                  placeholder="Get Started"
                  value={data.ctaSection.buttonText}
                  onChange={(e) =>
                    setData({
                      ...data,
                      ctaSection: {
                        ...data.ctaSection,
                        buttonText: e.target.value,
                      },
                    })
                  }
                />
                <AdminInput
                  label="Button link"
                  placeholder="/contact"
                  value={data.ctaSection.buttonLink}
                  onChange={(e) =>
                    setData({
                      ...data,
                      ctaSection: {
                        ...data.ctaSection,
                        buttonLink: e.target.value,
                      },
                    })
                  }
                />
              </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="button"
              variant="primary"
              onClick={handleSave}
              isLoading={saving}
              icon={faSave}
            >
              Save changes
            </AdminButton>
          </div>
        </AdminForm>
      </AdminCard>
    </>
  );
}
