'use client';

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

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();
}

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

  const [heroTitle, setHeroTitle] = useState<LocalizedString>(emptyLS());
  const [heroSubtitle, setHeroSubtitle] = useState<LocalizedString>(emptyLS());
  const [heroImage, setHeroImage] = useState('');
  const [heroCtaText, setHeroCtaText] = useState<LocalizedString>(emptyLS());
  const [heroCtaLink, setHeroCtaLink] = useState('');

  const [benefits, setBenefits] = useState<
    Array<{ title: LocalizedString; description: LocalizedString; highlight: LocalizedString }>
  >([]);

  const [sections, setSections] = useState<
    Array<{ title: LocalizedString; description: LocalizedString; image?: string; ctaText: LocalizedString; ctaLink: string }>
  >([]);

  const [ctaTitle, setCtaTitle] = useState<LocalizedString>(emptyLS());
  const [ctaHotline, setCtaHotline] = useState('');
  const [ctaButtonText, setCtaButtonText] = useState<LocalizedString>(emptyLS());
  const [ctaButtonLink, setCtaButtonLink] = useState('');

  const updateLS = (setter: React.Dispatch<React.SetStateAction<LocalizedString>>, lang: Lang, value: string) => {
    setter((prev) => ({ ...prev, [lang]: value }));
  };

  const loadFromData = (data: GolfIdData) => {
    setHeroTitle(asLS(data.heroTitle));
    setHeroSubtitle(asLS(data.heroSubtitle));
    setHeroImage(data.heroImage ?? '');
    setHeroCtaText(asLS(data.heroCtaText));
    setHeroCtaLink(data.heroCtaLink ?? '');
    setBenefits(
      (data.benefits ?? []).map((b) => ({
        title: asLS(b.title),
        description: asLS(b.description),
        highlight: asLS(b.highlight),
      }))
    );
    setSections(
      (data.sections ?? []).map((s) => ({
        title: asLS(s.title),
        description: asLS(s.description),
        image: s.image,
        ctaText: asLS(s.ctaText),
        ctaLink: s.ctaLink ?? '',
      }))
    );
    setCtaTitle(asLS(data.ctaTitle));
    setCtaHotline(data.ctaHotline ?? '');
    setCtaButtonText(asLS(data.ctaButtonText));
    setCtaButtonLink(data.ctaButtonLink ?? '');
  };

  useEffect(() => {
    api
      .getGolfId()
      .then(loadFromData)
      .catch(() => toast.error('Failed to load Golf ID data'))
      .finally(() => setIsLoading(false));
  }, []);

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSaving(true);
    try {
      const data: Partial<GolfIdData> = {
        heroTitle,
        heroSubtitle,
        heroImage: heroImage || undefined,
        heroCtaText,
        heroCtaLink: heroCtaLink || undefined,
        benefits,
        sections,
        ctaTitle,
        ctaHotline: ctaHotline || undefined,
        ctaButtonText,
        ctaButtonLink: ctaButtonLink || undefined,
      };
      const updated = await api.updateGolfId(data);
      loadFromData(updated);
      toast.success('Golf ID page saved');
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Failed to save');
    } finally {
      setIsSaving(false);
    }
  };

  const addBenefit = () =>
    setBenefits([...benefits, { title: emptyLS(), description: emptyLS(), highlight: emptyLS() }]);
  const removeBenefit = (idx: number) => setBenefits(benefits.filter((_, i) => i !== idx));
  const updateBenefitField = (
    idx: number,
    field: 'title' | 'description' | 'highlight',
    lang: Lang,
    value: string
  ) =>
    setBenefits(
      benefits.map((b, i) =>
        i === idx ? { ...b, [field]: { ...b[field], [lang]: value } } : b
      )
    );

  const addSection = () =>
    setSections([...sections, { title: emptyLS(), description: emptyLS(), image: undefined, ctaText: emptyLS(), ctaLink: '' }]);
  const removeSection = (idx: number) => setSections(sections.filter((_, i) => i !== idx));
  const updateSectionField = (idx: number, field: 'title' | 'description' | 'ctaText', lang: Lang, value: string) =>
    setSections(
      sections.map((s, i) =>
        i === idx ? { ...s, [field]: { ...(s[field] as LocalizedString), [lang]: value } } : s
      )
    );
  const updateSectionImage = (idx: number, image: string) =>
    setSections(sections.map((s, i) => (i === idx ? { ...s, image: image || undefined } : s)));
  const updateSectionCtaLink = (idx: number, ctaLink: string) =>
    setSections(sections.map((s, i) => (i === idx ? { ...s, ctaLink } : s)));

  if (isLoading) return <PageSpinner />;

  return (
    <div className="space-y-5">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-gray-900">Golf ID</h1>
        <Button type="submit" form="golf-id-form" isLoading={isSaving}>
          <Save size={16} />
          Save changes
        </Button>
      </div>

      <form id="golf-id-form" onSubmit={handleSave} className="space-y-5">
        <LanguageTabs activeLang={activeLang} onChange={setActiveLang} />

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
          <Section title="Hero Section">
            <Input
              label={`Title (${activeLang.toUpperCase()})`}
              value={heroTitle[activeLang]}
              onChange={(e) => updateLS(setHeroTitle, activeLang, e.target.value)}
              required
            />
            <Textarea
              label={`Subtitle (${activeLang.toUpperCase()})`}
              value={heroSubtitle[activeLang]}
              onChange={(e) => updateLS(setHeroSubtitle, activeLang, e.target.value)}
              rows={3}
            />
            <ImageUploader label="Hero background image" value={heroImage} onChange={setHeroImage} />
          </Section>

          <Section title="Hero CTA & Footer CTA">
            <Input
              label={`Hero CTA text (${activeLang.toUpperCase()})`}
              value={heroCtaText[activeLang]}
              onChange={(e) => updateLS(setHeroCtaText, activeLang, e.target.value)}
            />
            <Input
              label="Hero CTA link"
              value={heroCtaLink}
              onChange={(e) => setHeroCtaLink(e.target.value)}
              placeholder="https://golfcard.com.hk/register"
            />
            <hr className="border-gray-200" />
            <Input
              label={`Footer CTA title (${activeLang.toUpperCase()})`}
              value={ctaTitle[activeLang]}
              onChange={(e) => updateLS(setCtaTitle, activeLang, e.target.value)}
            />
            <Input
              label="Hotline"
              value={ctaHotline}
              onChange={(e) => setCtaHotline(e.target.value)}
              placeholder="(852) 3582-3088"
            />
            <Input
              label={`Footer CTA button text (${activeLang.toUpperCase()})`}
              value={ctaButtonText[activeLang]}
              onChange={(e) => updateLS(setCtaButtonText, activeLang, e.target.value)}
            />
            <Input
              label="Footer CTA link"
              value={ctaButtonLink}
              onChange={(e) => setCtaButtonLink(e.target.value)}
              placeholder="https://golfcard.com.hk/register"
            />
          </Section>
        </div>

        {/* Benefits Cards */}
        <Section title="Benefits Cards">
          <div className="space-y-4">
            {benefits.map((benefit, idx) => (
              <div key={idx} className="border border-gray-200 rounded-lg p-4 relative">
                <button
                  type="button"
                  onClick={() => removeBenefit(idx)}
                  className="absolute top-2 right-2 text-gray-400 hover:text-red-500"
                >
                  <X size={16} />
                </button>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                  <div className="space-y-2">
                    <label className="block text-sm font-medium text-gray-700">
                      Highlight ({activeLang.toUpperCase()})
                    </label>
                    <input
                      value={benefit.highlight[activeLang]}
                      onChange={(e) => updateBenefitField(idx, 'highlight', activeLang, e.target.value)}
                      placeholder="50%"
                      className="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </div>
                  <div className="space-y-2">
                    <label className="block text-sm font-medium text-gray-700">
                      Title ({activeLang.toUpperCase()})
                    </label>
                    <input
                      value={benefit.title[activeLang]}
                      onChange={(e) => updateBenefitField(idx, 'title', activeLang, e.target.value)}
                      placeholder={activeLang === 'en' ? 'Benefit title' : '權益標題'}
                      className="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </div>
                  <div className="space-y-2">
                    <label className="block text-sm font-medium text-gray-700">
                      Description ({activeLang.toUpperCase()})
                    </label>
                    <textarea
                      value={benefit.description[activeLang]}
                      onChange={(e) => updateBenefitField(idx, 'description', activeLang, e.target.value)}
                      placeholder={activeLang === 'en' ? 'Benefit description' : '權益描述'}
                      rows={2}
                      className="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
                    />
                  </div>
                </div>
              </div>
            ))}
          </div>
          <Button type="button" variant="secondary" size="sm" onClick={addBenefit}>
            <Plus size={14} />
            Add benefit
          </Button>
        </Section>

        {/* Offer Sections */}
        <Section title="Offer Sections">
          <p className="text-sm text-gray-500 -mt-1 mb-3">
            Each section displays as a large image+text showcase block on the frontend. Upload an image and set a CTA link to the relevant sub-page.
          </p>
          <div className="space-y-4">
            {sections.map((section, idx) => (
              <div key={idx} className="border border-gray-200 rounded-lg p-4 relative">
                <button
                  type="button"
                  onClick={() => removeSection(idx)}
                  className="absolute top-2 right-2 text-gray-400 hover:text-red-500"
                >
                  <X size={16} />
                </button>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-3">
                    <ImageUploader
                      label="Section image"
                      value={section.image || ''}
                      onChange={(v) => updateSectionImage(idx, v)}
                    />
                  </div>
                  <div className="space-y-3">
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Title ({activeLang.toUpperCase()})
                      </label>
                      <input
                        value={section.title[activeLang]}
                        onChange={(e) => updateSectionField(idx, 'title', activeLang, e.target.value)}
                        placeholder={activeLang === 'en' ? 'Section title' : '區塊標題'}
                        className="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Description ({activeLang.toUpperCase()})
                      </label>
                      <textarea
                        value={section.description[activeLang]}
                        onChange={(e) => updateSectionField(idx, 'description', activeLang, e.target.value)}
                        placeholder={activeLang === 'en' ? 'Section description' : '區塊描述'}
                        rows={3}
                        className="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        CTA Button Text ({activeLang.toUpperCase()})
                      </label>
                      <input
                        value={section.ctaText[activeLang]}
                        onChange={(e) => updateSectionField(idx, 'ctaText', activeLang, e.target.value)}
                        placeholder={activeLang === 'en' ? 'e.g. Welcome Offers' : '例如 迎新優惠'}
                        className="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">CTA Link</label>
                      <input
                        value={section.ctaLink}
                        onChange={(e) => updateSectionCtaLink(idx, e.target.value)}
                        placeholder="/golf-id/membership-offers"
                        className="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                      />
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
          <Button type="button" variant="secondary" size="sm" onClick={addSection}>
            <Plus size={14} />
            Add section
          </Button>
        </Section>

        <div className="flex justify-end">
          <Button type="submit" isLoading={isSaving} size="lg">
            <Save size={16} />
            Save changes
          </Button>
        </div>
      </form>
    </div>
  );
}
