'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 { GolfDevelopmentFundData, 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 GDFEditorPage() {
  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 [operationTitle, setOperationTitle] = useState<LocalizedString>(emptyLS());
  const [operationDescription, setOperationDescription] = useState<LocalizedString>(emptyLS());
  const [operationSteps, setOperationSteps] = useState<
    Array<{ title: LocalizedString; description: LocalizedString; image: string }>
  >([]);

  const [ctaTitle, setCtaTitle] = useState<LocalizedString>(emptyLS());
  const [ctaDescription, setCtaDescription] = useState<LocalizedString>(emptyLS());
  const [ctaButtonText, setCtaButtonText] = useState<LocalizedString>(emptyLS());
  const [ctaButtonUrl, setCtaButtonUrl] = useState('');

  const [investmentTitle, setInvestmentTitle] = useState<LocalizedString>(emptyLS());
  const [investmentDescription, setInvestmentDescription] = useState<LocalizedString>(emptyLS());
  const [investmentAreas, setInvestmentAreas] = useState<
    Array<{ title: LocalizedString; description: LocalizedString; image: string }>
  >([]);

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

  const loadFromData = (data: GolfDevelopmentFundData) => {
    setHeroTitle(asLS(data.heroTitle));
    setHeroSubtitle(asLS(data.heroSubtitle));
    setHeroImage(data.heroImage ?? '');
    setOperationTitle(asLS(data.operationTitle));
    setOperationDescription(asLS(data.operationDescription));
    setOperationSteps(
      (data.operationSteps ?? []).map((s) => ({
        title: asLS(s.title),
        description: asLS(s.description),
        image: s.image ?? '',
      }))
    );
    setCtaTitle(asLS(data.ctaBanner?.title));
    setCtaDescription(asLS(data.ctaBanner?.description));
    setCtaButtonText(asLS(data.ctaBanner?.buttonText));
    setCtaButtonUrl(data.ctaBanner?.buttonUrl ?? '');
    setInvestmentTitle(asLS(data.investmentTitle));
    setInvestmentDescription(asLS(data.investmentDescription));
    setInvestmentAreas(
      (data.investmentAreas ?? []).map((a) => ({
        title: asLS(a.title),
        description: asLS(a.description),
        image: a.image ?? '',
      }))
    );
  };

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

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSaving(true);
    try {
      const data: Partial<GolfDevelopmentFundData> = {
        heroTitle,
        heroSubtitle,
        heroImage: heroImage || undefined,
        operationTitle,
        operationDescription,
        operationSteps,
        ctaBanner: {
          title: ctaTitle,
          description: ctaDescription,
          buttonText: ctaButtonText,
          buttonUrl: ctaButtonUrl,
        },
        investmentTitle,
        investmentDescription,
        investmentAreas,
      };
      const updated = await api.updateGDF(data);
      loadFromData(updated);
      toast.success('Golf Development Fund page saved');
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Failed to save');
    } finally {
      setIsSaving(false);
    }
  };

  const addStep = () =>
    setOperationSteps([...operationSteps, { title: emptyLS(), description: emptyLS(), image: '' }]);
  const removeStep = (idx: number) => setOperationSteps(operationSteps.filter((_, i) => i !== idx));
  const updateStepField = (idx: number, field: 'title' | 'description', lang: Lang, value: string) =>
    setOperationSteps(operationSteps.map((s, i) => (i === idx ? { ...s, [field]: { ...s[field], [lang]: value } } : s)));
  const updateStepImage = (idx: number, image: string) =>
    setOperationSteps(operationSteps.map((s, i) => (i === idx ? { ...s, image } : s)));

  const addArea = () =>
    setInvestmentAreas([...investmentAreas, { title: emptyLS(), description: emptyLS(), image: '' }]);
  const removeArea = (idx: number) => setInvestmentAreas(investmentAreas.filter((_, i) => i !== idx));
  const updateAreaField = (idx: number, field: 'title' | 'description', lang: Lang, value: string) =>
    setInvestmentAreas(investmentAreas.map((a, i) => (i === idx ? { ...a, [field]: { ...a[field], [lang]: value } } : a)));
  const updateAreaImage = (idx: number, image: string) =>
    setInvestmentAreas(investmentAreas.map((a, i) => (i === idx ? { ...a, image } : a)));

  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 Development Fund</h1>
        <Button type="submit" form="gdf-form" isLoading={isSaving}>
          <Save size={16} />
          Save changes
        </Button>
      </div>

      <form id="gdf-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={2}
            />
            <ImageUploader label="Hero background image" value={heroImage} onChange={setHeroImage} />
          </Section>

          <Section title="Section Headings & Descriptions">
            <Input
              label={`Operation section title (${activeLang.toUpperCase()})`}
              value={operationTitle[activeLang]}
              onChange={(e) => updateLS(setOperationTitle, activeLang, e.target.value)}
            />
            <Textarea
              label={`Operation section description (${activeLang.toUpperCase()})`}
              value={operationDescription[activeLang]}
              onChange={(e) => updateLS(setOperationDescription, activeLang, e.target.value)}
              rows={2}
            />
            <Input
              label={`Investment section title (${activeLang.toUpperCase()})`}
              value={investmentTitle[activeLang]}
              onChange={(e) => updateLS(setInvestmentTitle, activeLang, e.target.value)}
            />
            <Textarea
              label={`Investment section description (${activeLang.toUpperCase()})`}
              value={investmentDescription[activeLang]}
              onChange={(e) => updateLS(setInvestmentDescription, activeLang, e.target.value)}
              rows={2}
            />
          </Section>
        </div>

        {/* CTA Banner */}
        <Section title="CTA Banner">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <Input
              label={`Title (${activeLang.toUpperCase()})`}
              value={ctaTitle[activeLang]}
              onChange={(e) => updateLS(setCtaTitle, activeLang, e.target.value)}
            />
            <Textarea
              label={`Description (${activeLang.toUpperCase()})`}
              value={ctaDescription[activeLang]}
              onChange={(e) => updateLS(setCtaDescription, activeLang, e.target.value)}
              rows={2}
            />
            <Input
              label={`Button text (${activeLang.toUpperCase()})`}
              value={ctaButtonText[activeLang]}
              onChange={(e) => updateLS(setCtaButtonText, activeLang, e.target.value)}
            />
            <Input
              label="Button URL"
              value={ctaButtonUrl}
              onChange={(e) => setCtaButtonUrl(e.target.value)}
              placeholder="/golf-id"
            />
          </div>
        </Section>

        {/* Operation Steps */}
        <Section title="Operation Steps">
          <div className="space-y-4">
            {operationSteps.map((step, idx) => (
              <div key={idx} className="border border-gray-200 rounded-lg p-4 relative">
                <button
                  type="button"
                  onClick={() => removeStep(idx)}
                  className="absolute top-2 right-2 text-gray-400 hover:text-red-500"
                >
                  <X size={16} />
                </button>
                <div className="flex items-center gap-2 mb-3">
                  <span className="w-7 h-7 rounded-full bg-blue-600 text-white text-sm font-bold flex items-center justify-center">
                    {idx + 1}
                  </span>
                  <span className="text-sm font-medium text-gray-600">Step {idx + 1}</span>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                  <div>
                    <ImageUploader
                      label="Image"
                      value={step.image}
                      onChange={(url) => updateStepImage(idx, url)}
                      previewHeight="h-24"
                    />
                  </div>
                  <div className="space-y-2">
                    <label className="block text-sm font-medium text-gray-700">
                      Title ({activeLang.toUpperCase()})
                    </label>
                    <input
                      value={step.title[activeLang]}
                      onChange={(e) => updateStepField(idx, 'title', activeLang, e.target.value)}
                      placeholder={activeLang === 'en' ? 'Step 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={step.description[activeLang]}
                      onChange={(e) => updateStepField(idx, 'description', activeLang, e.target.value)}
                      placeholder={activeLang === 'en' ? 'Step 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={addStep}>
            <Plus size={14} />
            Add step
          </Button>
        </Section>

        {/* Investment Areas */}
        <Section title="Investment Areas">
          <div className="space-y-4">
            {investmentAreas.map((area, idx) => (
              <div key={idx} className="border border-gray-200 rounded-lg p-4 relative">
                <button
                  type="button"
                  onClick={() => removeArea(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>
                    <ImageUploader
                      label="Image"
                      value={area.image}
                      onChange={(url) => updateAreaImage(idx, url)}
                      previewHeight="h-24"
                    />
                  </div>
                  <div className="space-y-2">
                    <label className="block text-sm font-medium text-gray-700">
                      Title ({activeLang.toUpperCase()})
                    </label>
                    <input
                      value={area.title[activeLang]}
                      onChange={(e) => updateAreaField(idx, 'title', activeLang, e.target.value)}
                      placeholder={activeLang === 'en' ? 'Area 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={area.description[activeLang]}
                      onChange={(e) => updateAreaField(idx, 'description', activeLang, e.target.value)}
                      placeholder={activeLang === 'en' ? 'Area 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={addArea}>
            <Plus size={14} />
            Add investment area
          </Button>
        </Section>

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