'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 { GroupServicesData, 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';

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 GroupServicesEditorPage() {
  const { activeLang, setActiveLang } = useLanguageTabs();
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);

  // Hero
  const [heroTitle, setHeroTitle] = useState<LocalizedString>(emptyLS());
  const [heroSubtitle, setHeroSubtitle] = useState<LocalizedString>(emptyLS());
  const [heroImage, setHeroImage] = useState('');

  // Advantages
  const [advantagesTitle, setAdvantagesTitle] = useState<LocalizedString>(emptyLS());
  const [advantagesDescription, setAdvantagesDescription] = useState<LocalizedString>(emptyLS());
  const [advantages, setAdvantages] = useState<Array<{ image: string; title: LocalizedString; description: LocalizedString }>>([]);

  // Services
  const [servicesTitle, setServicesTitle] = useState<LocalizedString>(emptyLS());
  const [serviceItems, setServiceItems] = useState<Array<{ title: LocalizedString; description: LocalizedString }>>([]);

  // Tournaments
  const [tournamentsTitle, setTournamentsTitle] = useState<LocalizedString>(emptyLS());
  const [tournamentItems, setTournamentItems] = useState<Array<{ title: LocalizedString; details: LocalizedString[] }>>([]);

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

  const loadFromData = (data: GroupServicesData) => {
    setHeroTitle(asLS(data.heroTitle));
    setHeroSubtitle(asLS(data.heroSubtitle));
    setHeroImage(data.heroImage ?? '');
    setAdvantagesTitle(asLS(data.advantagesTitle));
    setAdvantagesDescription(asLS(data.advantagesDescription));
    setAdvantages(
      (data.advantages ?? []).map((a) => ({
        image: a.image ?? '',
        title: asLS(a.title),
        description: asLS(a.description),
      }))
    );
    setServicesTitle(asLS(data.servicesTitle));
    setServiceItems(
      (data.serviceItems ?? []).map((s) => ({
        title: asLS(s.title),
        description: asLS(s.description),
      }))
    );
    setTournamentsTitle(asLS(data.tournamentsTitle));
    setTournamentItems(
      (data.tournamentItems ?? []).map((t) => ({
        title: asLS(t.title),
        details: (t.details ?? []).map((d) => asLS(d)),
      }))
    );
  };

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

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSaving(true);
    try {
      const data: Partial<GroupServicesData> = {
        heroTitle,
        heroSubtitle,
        heroImage: heroImage || undefined,
        advantagesTitle,
        advantagesDescription,
        advantages,
        servicesTitle,
        serviceItems,
        tournamentsTitle,
        tournamentItems,
      };
      const updated = await api.updateGroupServices(data);
      loadFromData(updated);
      toast.success('Group Services page saved');
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Failed to save');
    } finally {
      setIsSaving(false);
    }
  };

  // Advantage helpers
  const addAdvantage = () => setAdvantages([...advantages, { image: '', title: emptyLS(), description: emptyLS() }]);
  const removeAdvantage = (idx: number) => setAdvantages(advantages.filter((_, i) => i !== idx));
  const updateAdvantageField = (idx: number, field: 'title' | 'description', lang: Lang, value: string) =>
    setAdvantages(advantages.map((a, i) => (i === idx ? { ...a, [field]: { ...a[field], [lang]: value } } : a)));
  const updateAdvantageImage = (idx: number, image: string) =>
    setAdvantages(advantages.map((a, i) => (i === idx ? { ...a, image } : a)));

  // Service item helpers
  const addServiceItem = () => setServiceItems([...serviceItems, { title: emptyLS(), description: emptyLS() }]);
  const removeServiceItem = (idx: number) => setServiceItems(serviceItems.filter((_, i) => i !== idx));
  const updateServiceField = (idx: number, field: 'title' | 'description', lang: Lang, value: string) =>
    setServiceItems(serviceItems.map((s, i) => (i === idx ? { ...s, [field]: { ...s[field], [lang]: value } } : s)));

  // Tournament item helpers
  const addTournamentItem = () => setTournamentItems([...tournamentItems, { title: emptyLS(), details: [] }]);
  const removeTournamentItem = (idx: number) => setTournamentItems(tournamentItems.filter((_, i) => i !== idx));
  const updateTournamentTitle = (idx: number, lang: Lang, value: string) =>
    setTournamentItems(tournamentItems.map((t, i) => (i === idx ? { ...t, title: { ...t.title, [lang]: value } } : t)));
  const addTournamentDetail = (idx: number) =>
    setTournamentItems(tournamentItems.map((t, i) => (i === idx ? { ...t, details: [...t.details, emptyLS()] } : t)));
  const removeTournamentDetail = (tIdx: number, dIdx: number) =>
    setTournamentItems(tournamentItems.map((t, i) => (i === tIdx ? { ...t, details: t.details.filter((_, j) => j !== dIdx) } : t)));
  const updateTournamentDetail = (tIdx: number, dIdx: number, lang: Lang, value: string) =>
    setTournamentItems(
      tournamentItems.map((t, i) =>
        i === tIdx
          ? { ...t, details: t.details.map((d, j) => (j === dIdx ? { ...d, [lang]: value } : d)) }
          : t
      )
    );

  if (isLoading) return <PageSpinner />;

  const Section = ({ title, children }: { title: string; children: React.ReactNode }) => (
    <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
      <div className="px-5 py-3.5 border-b border-gray-100 bg-gray-50">
        <h2 className="text-sm font-semibold text-gray-700">{title}</h2>
      </div>
      <div className="p-5 space-y-4">{children}</div>
    </div>
  );

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

      <form id="group-services-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="Advantages Intro">
            <Input
              label={`Section title (${activeLang.toUpperCase()})`}
              value={advantagesTitle[activeLang]}
              onChange={(e) => updateLS(setAdvantagesTitle, activeLang, e.target.value)}
            />
            <Textarea
              label={`Description (${activeLang.toUpperCase()})`}
              value={advantagesDescription[activeLang]}
              onChange={(e) => updateLS(setAdvantagesDescription, activeLang, e.target.value)}
              rows={4}
            />
          </Section>
        </div>

        {/* Advantages */}
        <Section title="Advantages">
          <div className="space-y-4">
            {advantages.map((adv, idx) => (
              <div key={idx} className="border border-gray-200 rounded-lg p-4 relative">
                <button type="button" onClick={() => removeAdvantage(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={adv.image} onChange={(url) => updateAdvantageImage(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={adv.title[activeLang]}
                      onChange={(e) => updateAdvantageField(idx, 'title', activeLang, e.target.value)}
                      placeholder={activeLang === 'en' ? 'Advantage 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={adv.description[activeLang]}
                      onChange={(e) => updateAdvantageField(idx, 'description', activeLang, e.target.value)}
                      placeholder={activeLang === 'en' ? 'Advantage 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={addAdvantage}>
            <Plus size={14} />
            Add advantage
          </Button>
        </Section>

        {/* Services Include */}
        <Section title="Services Include">
          <Input
            label={`Section title (${activeLang.toUpperCase()})`}
            value={servicesTitle[activeLang]}
            onChange={(e) => updateLS(setServicesTitle, activeLang, e.target.value)}
          />
          <div className="space-y-3">
            {serviceItems.map((svc, idx) => (
              <div key={idx} className="border border-gray-200 rounded-lg p-4 relative">
                <button type="button" onClick={() => removeServiceItem(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-3">
                  <div className="space-y-1.5">
                    <label className="block text-sm font-medium text-gray-700">Title ({activeLang.toUpperCase()})</label>
                    <input
                      value={svc.title[activeLang]}
                      onChange={(e) => updateServiceField(idx, 'title', activeLang, e.target.value)}
                      placeholder={activeLang === 'en' ? 'Service 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-1.5">
                    <label className="block text-sm font-medium text-gray-700">Description ({activeLang.toUpperCase()})</label>
                    <input
                      value={svc.description[activeLang]}
                      onChange={(e) => updateServiceField(idx, 'description', activeLang, e.target.value)}
                      placeholder={activeLang === 'en' ? 'Service description' : '服務描述'}
                      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>
          <Button type="button" variant="secondary" size="sm" onClick={addServiceItem}>
            <Plus size={14} />
            Add service
          </Button>
        </Section>

        {/* Tournaments Include */}
        <Section title="Tournaments Include">
          <Input
            label={`Section title (${activeLang.toUpperCase()})`}
            value={tournamentsTitle[activeLang]}
            onChange={(e) => updateLS(setTournamentsTitle, activeLang, e.target.value)}
          />
          <div className="space-y-4">
            {tournamentItems.map((item, tIdx) => (
              <div key={tIdx} className="border border-gray-200 rounded-lg p-4 relative">
                <button type="button" onClick={() => removeTournamentItem(tIdx)} className="absolute top-2 right-2 text-gray-400 hover:text-red-500">
                  <X size={16} />
                </button>
                <div className="space-y-3">
                  <div className="space-y-1.5">
                    <label className="block text-sm font-medium text-gray-700">Title ({activeLang.toUpperCase()})</label>
                    <input
                      value={item.title[activeLang]}
                      onChange={(e) => updateTournamentTitle(tIdx, activeLang, e.target.value)}
                      placeholder={activeLang === 'en' ? 'Tournament item 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-xs font-medium text-gray-500 uppercase tracking-wider">Details / Bullet Points</label>
                    {item.details.map((detail, dIdx) => (
                      <div key={dIdx} className="flex gap-2 items-start">
                        <span className="text-gray-400 mt-2 text-sm">&#10003;</span>
                        <input
                          value={detail[activeLang]}
                          onChange={(e) => updateTournamentDetail(tIdx, dIdx, activeLang, e.target.value)}
                          placeholder={activeLang === 'en' ? `Detail ${dIdx + 1}` : `詳情 ${dIdx + 1}`}
                          className="flex-1 px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                        />
                        <button type="button" onClick={() => removeTournamentDetail(tIdx, dIdx)} className="mt-2 text-gray-400 hover:text-red-500">
                          <X size={14} />
                        </button>
                      </div>
                    ))}
                    <button
                      type="button"
                      onClick={() => addTournamentDetail(tIdx)}
                      className="text-xs text-blue-600 hover:text-blue-700 font-medium"
                    >
                      + Add detail
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
          <Button type="button" variant="secondary" size="sm" onClick={addTournamentItem}>
            <Plus size={14} />
            Add tournament item
          </Button>
        </Section>

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