'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 { GolfServicesPageData, 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();
}

interface CardItem {
  image: string;
  title: LocalizedString;
  description: LocalizedString;
  link: string;
}

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

  const [heroTitle, setHeroTitle] = useState<LocalizedString>(emptyLS());
  const [heroDescription, setHeroDescription] = useState<LocalizedString>(emptyLS());
  const [serviceCards, setServiceCards] = useState<CardItem[]>([]);

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

  const loadFromData = (data: GolfServicesPageData) => {
    setHeroTitle(asLS(data.heroTitle));
    setHeroDescription(asLS(data.heroDescription));
    setServiceCards(
      (data.serviceCards ?? []).map((c) => ({
        image: c.image ?? '',
        title: asLS(c.title),
        description: asLS(c.description),
        link: c.link ?? '',
      }))
    );
  };

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

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSaving(true);
    try {
      const data: Partial<GolfServicesPageData> = {
        heroTitle,
        heroDescription,
        serviceCards,
      };
      const updated = await api.updateGolfServicesPage(data);
      loadFromData(updated);
      toast.success('Golf Services page saved');
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Failed to save');
    } finally {
      setIsSaving(false);
    }
  };

  const addCard = () =>
    setServiceCards([...serviceCards, { image: '', title: emptyLS(), description: emptyLS(), link: '' }]);

  const removeCard = (idx: number) => setServiceCards(serviceCards.filter((_, i) => i !== idx));

  const updateCardLS = (idx: number, field: 'title' | 'description', lang: Lang, value: string) =>
    setServiceCards(
      serviceCards.map((c, i) =>
        i === idx ? { ...c, [field]: { ...c[field], [lang]: value } } : c
      )
    );

  const updateCardField = (idx: number, field: 'image' | 'link', value: string) =>
    setServiceCards(serviceCards.map((c, i) => (i === idx ? { ...c, [field]: value } : c)));

  if (isLoading) return <PageSpinner />;

  return (
    <div className="space-y-5">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Golf Services</h1>
          <p className="text-sm text-gray-500 mt-0.5">Landing page for the Our Services section</p>
        </div>
        <Button type="submit" form="golf-services-form" isLoading={isSaving}>
          <Save size={16} />
          Save changes
        </Button>
      </div>

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

        <Section title="Hero Section">
          <Input
            label={`Title (${activeLang.toUpperCase()})`}
            value={heroTitle[activeLang]}
            onChange={(e) => updateLS(setHeroTitle, activeLang, e.target.value)}
            required
            placeholder={activeLang === 'en' ? 'Golf Services' : '高爾夫服務'}
          />
          <Textarea
            label={`Description (${activeLang.toUpperCase()})`}
            value={heroDescription[activeLang]}
            onChange={(e) => updateLS(setHeroDescription, activeLang, e.target.value)}
            rows={3}
            placeholder={activeLang === 'en' ? 'Describe the services...' : '描述服務內容...'}
          />
        </Section>

        <Section title={`Service Cards (${serviceCards.length})`}>
          <p className="text-xs text-gray-500">
            Each card links to a dedicated sub-page. Add an image, title, description, and the page link.
          </p>
          <div className="space-y-6">
            {serviceCards.map((card, idx) => (
              <div key={idx} className="border border-gray-200 rounded-lg p-4 relative">
                <button
                  type="button"
                  onClick={() => removeCard(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-4">
                  <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">
                    {card.title.en || `Card ${idx + 1}`}
                  </span>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-3">
                    <Input
                      label={`Title (${activeLang.toUpperCase()})`}
                      value={card.title[activeLang]}
                      onChange={(e) => updateCardLS(idx, 'title', activeLang, e.target.value)}
                      placeholder={activeLang === 'en' ? 'e.g. Group Services' : '例：團體服務'}
                    />
                    <Textarea
                      label={`Description (${activeLang.toUpperCase()})`}
                      value={card.description[activeLang]}
                      onChange={(e) => updateCardLS(idx, 'description', activeLang, e.target.value)}
                      rows={3}
                      placeholder={activeLang === 'en' ? 'Brief description...' : '簡短描述...'}
                    />
                    <Input
                      label="Link path"
                      value={card.link}
                      onChange={(e) => updateCardField(idx, 'link', e.target.value)}
                      placeholder="/services/events"
                      hint="Route to the sub-page (e.g. /services/events)"
                    />
                  </div>
                  <ImageUploader
                    label="Card image"
                    value={card.image}
                    onChange={(url) => updateCardField(idx, 'image', url)}
                    previewHeight="h-40"
                  />
                </div>
              </div>
            ))}
          </div>
          <Button type="button" variant="secondary" size="sm" onClick={addCard}>
            <Plus size={14} />
            Add card
          </Button>
        </Section>

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