'use client';

import { useEffect, useState } from 'react';
import { Save } from 'lucide-react';
import toast from 'react-hot-toast';
import api from '@/lib/api';
import { SiteSettings, LocalizedString } from '@/types';
import Button from '@/components/ui/Button';
import Input from '@/components/ui/Input';
import ImageUploader from '@/components/ui/ImageUploader';
import { PageSpinner } from '@/components/ui/Spinner';
import LanguageTabs, { useLanguageTabs, Lang } from '@/components/ui/LanguageTabs';

const emptyLS = (): LocalizedString => ({ en: '', zh: '' });

function asLS(val: unknown): LocalizedString {
  if (val && typeof val === 'object' && 'en' in val) return val as LocalizedString;
  if (typeof val === 'string') return { en: val, zh: '' };
  return emptyLS();
}

interface PromoState {
  image: string;
  title: LocalizedString;
  link: string;
}

const emptyPromo = (): PromoState => ({ image: '', title: emptyLS(), link: '' });

const PANELS = [
  { key: 'services' as const, label: 'Services Menu', description: 'Promotional card shown in the Services mega menu dropdown.' },
  { key: 'about' as const, label: 'About Us Menu', description: 'Promotional card shown in the About Us mega menu dropdown.' },
  { key: 'golfId' as const, label: 'Golf ID Menu', description: 'Promotional card shown in the Golf ID mega menu dropdown.' },
];

type NavLabelKey = 'home' | 'about' | 'services' | 'eventGallery' | 'golfId';

const NAV_ITEMS: Array<{ key: NavLabelKey; defaultLabel: string }> = [
  { key: 'home', defaultLabel: 'Home' },
  { key: 'about', defaultLabel: 'About Us' },
  { key: 'services', defaultLabel: 'Our Services' },
  { key: 'eventGallery', defaultLabel: 'Event Gallery' },
  { key: 'golfId', defaultLabel: 'Golf ID' },
];

export default function NavigationPage() {
  const { activeLang, setActiveLang } = useLanguageTabs();
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);

  const [promos, setPromos] = useState<Record<'services' | 'about' | 'golfId', PromoState>>({
    services: emptyPromo(),
    about: emptyPromo(),
    golfId: emptyPromo(),
  });

  const [navLabels, setNavLabels] = useState<Record<NavLabelKey, LocalizedString>>({
    home: emptyLS(),
    about: emptyLS(),
    services: emptyLS(),
    eventGallery: emptyLS(),
    golfId: emptyLS(),
  });

  const loadFromData = (data: SiteSettings) => {
    const mp = data.navigation?.megaMenuPromos;
    setPromos({
      services: {
        image: mp?.services?.image ?? '',
        title: asLS(mp?.services?.title),
        link: mp?.services?.link ?? '',
      },
      about: {
        image: mp?.about?.image ?? '',
        title: asLS(mp?.about?.title),
        link: mp?.about?.link ?? '',
      },
      golfId: {
        image: mp?.golfId?.image ?? '',
        title: asLS(mp?.golfId?.title),
        link: mp?.golfId?.link ?? '',
      },
    });

    const nl = data.navigation?.navLabels;
    setNavLabels({
      home: asLS(nl?.home),
      about: asLS(nl?.about),
      services: asLS(nl?.services),
      eventGallery: asLS(nl?.eventGallery),
      golfId: asLS(nl?.golfId),
    });
  };

  useEffect(() => {
    api
      .getSettings()
      .then(loadFromData)
      .catch(() => toast.error('Failed to load navigation settings'))
      .finally(() => setIsLoading(false));
  }, []);

  const updatePromo = (key: 'services' | 'about' | 'golfId', field: keyof PromoState, value: string) => {
    setPromos((prev) => ({
      ...prev,
      [key]: { ...prev[key], [field]: value },
    }));
  };

  const updateNavLabel = (key: NavLabelKey, lang: Lang, value: string) => {
    setNavLabels((prev) => ({
      ...prev,
      [key]: { ...prev[key], [lang]: value },
    }));
  };

  const updatePromoTitle = (key: 'services' | 'about' | 'golfId', lang: Lang, value: string) => {
    setPromos((prev) => ({
      ...prev,
      [key]: { ...prev[key], title: { ...prev[key].title, [lang]: value } },
    }));
  };

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSaving(true);
    try {
      const payload = {
        navigation: {
          megaMenuPromos: {
            services: { image: promos.services.image, title: promos.services.title, link: promos.services.link },
            about: { image: promos.about.image, title: promos.about.title, link: promos.about.link },
            golfId: { image: promos.golfId.image, title: promos.golfId.title, link: promos.golfId.link },
          },
          navLabels,
        },
      };
      const updated = await api.updateSettings(payload);
      loadFromData(updated);
      toast.success('Navigation settings saved');
    } catch {
      toast.error('Failed to save navigation settings');
    } finally {
      setIsSaving(false);
    }
  };

  if (isLoading) return <PageSpinner />;

  return (
    <form onSubmit={handleSave} className="space-y-10 max-w-4xl">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Navigation</h1>
          <p className="text-gray-500 mt-1">Manage navigation bar labels and mega menu promotional images</p>
        </div>
        <Button type="submit" isLoading={isSaving}>
          <Save size={16} className="mr-2" /> Save Changes
        </Button>
      </div>

      <LanguageTabs activeLang={activeLang} onChange={setActiveLang} />

      {/* Nav Bar Labels */}
      <section className="bg-white rounded-xl border border-gray-200 p-6 space-y-4">
        <h2 className="text-lg font-semibold text-gray-800">Navigation Bar Labels</h2>
        <p className="text-sm text-gray-500">
          Customize the display name for each top-level navigation button. Leave blank to use the default.
        </p>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {NAV_ITEMS.map(({ key, defaultLabel }) => (
            <Input
              key={key}
              label={defaultLabel}
              value={navLabels[key][activeLang]}
              onChange={(e) => updateNavLabel(key, activeLang, e.target.value)}
              placeholder={defaultLabel}
            />
          ))}
        </div>
      </section>

      {PANELS.map(({ key, label, description }) => (
        <section key={key} className="bg-white rounded-xl border border-gray-200 p-6 space-y-4">
          <h2 className="text-lg font-semibold text-gray-800">{label}</h2>
          <p className="text-sm text-gray-500">{description}</p>
          <ImageUploader
            label="Promo Image"
            value={promos[key].image}
            onChange={(url) => updatePromo(key, 'image', url)}
            hint="Recommended: 480×360px (4:3 aspect ratio)"
          />
          <Input
            label="Promo Title"
            value={promos[key].title[activeLang]}
            onChange={(e) => updatePromoTitle(key, activeLang, e.target.value)}
            placeholder="e.g. New Academy Open Day"
          />
          <Input
            label="Promo Link"
            value={promos[key].link}
            onChange={(e) => updatePromo(key, 'link', e.target.value)}
            placeholder="/news/my-article or https://..."
          />
        </section>
      ))}

      <div className="flex justify-end pb-8">
        <Button type="submit" isLoading={isSaving}>
          <Save size={16} className="mr-2" /> Save Changes
        </Button>
      </div>
    </form>
  );
}
