"use client";

import { faPlus, faLightbulb } from "@fortawesome/free-solid-svg-icons";
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 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 AdminDataGrid from "@/components/admin/AdminDataGrid";
import AdminEmptyState from "@/components/admin/AdminEmptyState";
import AdminFormModal from "@/components/admin/AdminFormModal";
import AdminConfirmDialog from "@/components/admin/AdminConfirmDialog";
import AdminEditDeleteButtons from "@/components/admin/AdminEditDeleteButtons";
import AdminLoadingState from "@/components/admin/AdminLoadingState";
import { adminFetch } from "@/lib/adminFetch";

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

interface Feature {
  title: string;
  description: string;
  icon: string;
}

interface WattsContent {
  title: string;
  subtitle: string;
  features: Feature[];
}

export default function WattsTab() {
  const [content, setContent] = useState<WattsContent>({
    title: "",
    subtitle: "",
    features: [],
  });
  const [newFeature, setNewFeature] = useState<Feature>({
    title: "",
    description: "",
    icon: "💡",
  });
  const [editingIndex, setEditingIndex] = useState<number | null>(null);
  const [showEditor, setShowEditor] = useState(false);
  const [iconPickerOpen, setIconPickerOpen] = useState(false);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [deleteConfirm, setDeleteConfirm] = useState<{
    isOpen: boolean;
    index: number | null;
  }>({ isOpen: false, index: null });
  const iconPickerTriggerRef = useRef<HTMLDivElement>(null);
  const pickerRef = useRef<HTMLDivElement>(null);
  const { toast, showSuccess, showError, hideToast } = useAdminToast();

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

  useEffect(() => {
    const handleClick = (e: MouseEvent) => {
      const target = e.target as Node;
      const inPicker = pickerRef.current?.contains(target);
      const inTrigger = iconPickerTriggerRef.current?.contains(target);
      if (!inPicker && !inTrigger) setIconPickerOpen(false);
    };
    document.addEventListener("mousedown", handleClick);
    return () => document.removeEventListener("mousedown", handleClick);
  }, []);

  const resetFeatureForm = () => {
    setNewFeature({ title: "", description: "", icon: "💡" });
    setEditingIndex(null);
    setShowEditor(false);
  };

  const handleSaveFeature = async () => {
    try {
      const features =
        editingIndex !== null
          ? content.features.map((f, i) => (i === editingIndex ? newFeature : f))
          : [...content.features, newFeature];
      const updated = { ...content, features };
      const response = await adminFetch("/api/watts", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(updated),
      });
      if (!response.ok) throw new Error();
      setContent(updated);
      showSuccess(
        editingIndex !== null ? "Feature updated successfully!" : "Feature added successfully!",
      );
      resetFeatureForm();
    } catch {
      showError("Failed to save feature. Please try again.");
    }
  };

  const handleDeleteFeature = async (index: number) => {
    try {
      const features = content.features.filter((_, i) => i !== index);
      const updated = { ...content, features };
      const response = await adminFetch("/api/watts", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(updated),
      });
      if (!response.ok) throw new Error();
      setContent(updated);
      showSuccess("Feature deleted successfully!");
    } catch {
      showError("Failed to delete feature. Please try again.");
    } finally {
      setDeleteConfirm({ isOpen: false, index: null });
    }
  };

  const startEdit = (feature: Feature, index: number) => {
    setNewFeature({ ...feature });
    setEditingIndex(index);
    setShowEditor(true);
  };

  const handleSaveContent = async () => {
    setSaving(true);
    try {
      const response = await adminFetch("/api/watts", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(content),
      });
      if (!response.ok) throw new Error();
      showSuccess("Watts section saved successfully!");
    } catch {
      showError("Failed to save Watts section.");
    } finally {
      setSaving(false);
    }
  };

  const handleEmojiClick = (data: EmojiClickData) => {
    setNewFeature({ ...newFeature, icon: data.emoji });
    setIconPickerOpen(false);
  };

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

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

      <AdminConfirmDialog
        isOpen={deleteConfirm.isOpen}
        onClose={() => setDeleteConfirm({ isOpen: false, index: null })}
        onConfirm={() =>
          deleteConfirm.index !== null && handleDeleteFeature(deleteConfirm.index)
        }
        title="Delete feature"
        message="Are you sure you want to delete this feature? This action cannot be undone."
      />

      <div className="space-y-6">
        <AdminCard>
          <AdminForm onSubmit={(e) => e.preventDefault()}>
            <AdminSection title="Main content">
              <AdminInput
                label="Title"
                placeholder="Enter section title"
                value={content.title}
                onChange={(e) => setContent({ ...content, title: e.target.value })}
              />
              <AdminTextarea
                label="Subtitle"
                placeholder="Enter section subtitle"
                value={content.subtitle}
                onChange={(e) => setContent({ ...content, subtitle: e.target.value })}
                rows={4}
              />
            </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={handleSaveContent} isLoading={saving}>
                Save section
              </AdminButton>
            </div>
          </AdminForm>
        </AdminCard>

        <AdminCard
          header={
            <div className="flex items-center justify-between">
              <div>
                <h3 className="text-sm font-semibold text-slate-100">Features</h3>
                <p className="text-xs text-slate-400">Highlight key features</p>
              </div>
              <AdminButton
                variant="primary"
                size="sm"
                icon={faPlus}
                onClick={() => {
                  setEditingIndex(null);
                  setNewFeature({ title: "", description: "", icon: "💡" });
                  setShowEditor(true);
                }}
              >
                Add feature
              </AdminButton>
            </div>
          }
        >
          {content.features.length === 0 ? (
            <AdminEmptyState
              title="No features yet"
              description="Add your first feature"
              icon={faLightbulb}
              action={{ label: "Add feature", onClick: () => setShowEditor(true) }}
            />
          ) : (
            <AdminDataGrid columns={3} gap="md">
              {content.features.map((feature, index) => (
                <div
                  key={index}
                  className="group relative flex flex-col items-center rounded-lg border border-slate-800 bg-slate-900/60 p-5 text-center"
                >
                  <div className="mb-3 text-3xl">{feature.icon}</div>
                  <h3 className="mb-1 text-base font-semibold text-slate-100">
                    {feature.title}
                  </h3>
                  <p className="text-sm text-slate-400">{feature.description}</p>
                  <div className="absolute right-2 top-2 opacity-0 transition-opacity group-hover:opacity-100">
                    <AdminEditDeleteButtons
                      onEdit={() => startEdit(feature, index)}
                      onDelete={() =>
                        setDeleteConfirm({ isOpen: true, index })
                      }
                      size="sm"
                    />
                  </div>
                </div>
              ))}
            </AdminDataGrid>
          )}
        </AdminCard>
      </div>

      <AdminFormModal
        isOpen={showEditor}
        onClose={resetFeatureForm}
        title={editingIndex !== null ? "Edit feature" : "Add new feature"}
        onSubmit={handleSaveFeature}
        submitLabel={editingIndex !== null ? "Save changes" : "Add feature"}
      >
        <AdminInput
          label="Title"
          placeholder="Feature title"
          value={newFeature.title}
          onChange={(e) => setNewFeature({ ...newFeature, title: e.target.value })}
          required
        />
        <AdminTextarea
          label="Description"
          placeholder="Feature description"
          value={newFeature.description}
          onChange={(e) => setNewFeature({ ...newFeature, description: e.target.value })}
          rows={3}
          required
        />
        <div>
          <label className="mb-1.5 block text-sm font-medium text-slate-300">Icon</label>
          <div ref={iconPickerTriggerRef} className="relative inline-block">
            <button
              type="button"
              className="flex h-12 w-12 items-center justify-center rounded-lg border border-slate-800 bg-slate-950 text-2xl transition-colors hover:border-slate-700"
              onClick={() => setIconPickerOpen((v) => !v)}
              aria-label="Pick icon"
            >
              {newFeature.icon}
            </button>
            {iconPickerOpen && (
              <div ref={pickerRef} className="absolute z-50 mt-2">
                <Picker
                  onEmojiClick={handleEmojiClick}
                  theme={Theme.DARK}
                  width={350}
                  height={400}
                  searchPlaceholder="Search emojis..."
                  emojiStyle={EmojiStyle.NATIVE}
                  autoFocusSearch={false}
                  skinTonesDisabled
                  searchDisabled={false}
                  previewConfig={{ showPreview: false }}
                />
              </div>
            )}
          </div>
        </div>
      </AdminFormModal>
    </>
  );
}
