'use client';

import { useEffect, useState } from 'react';
import { Plus, X, Save, ArrowUp, ArrowDown } from 'lucide-react';
import toast from 'react-hot-toast';
import api from '@/lib/api';
import { AboutPageData, LocalizedString } from '@/types';
import Button from '@/components/ui/Button';
import Input, { Textarea } from '@/components/ui/Input';
import ImageUploader from '@/components/ui/ImageUploader';
import RichTextEditor from '@/components/RichTextEditor';
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 ContentSection {
  label: LocalizedString;
  title: LocalizedString;
  content: LocalizedString;
  image: string;
  imagePosition: string;
}

export default function AboutEditorPage() {
  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 [introTitle, setIntroTitle] = useState<LocalizedString>(emptyLS());
  const [introContent, setIntroContent] = useState<LocalizedString>(emptyLS());
  const [introImage, setIntroImage] = useState('');
  const [contentSections, setContentSections] = useState<ContentSection[]>([]);
  const [galleryImages, setGalleryImages] = useState<string[]>([]);
  const [ctaTitle, setCtaTitle] = useState<LocalizedString>(emptyLS());
  const [ctaDescription, setCtaDescription] = useState<LocalizedString>(emptyLS());
  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: AboutPageData) => {
    setHeroTitle(asLS(data.heroTitle));
    setHeroSubtitle(asLS(data.heroSubtitle));
    setHeroImage(data.heroImage ?? '');
    setIntroTitle(asLS(data.introTitle));
    setIntroContent(asLS(data.introContent));
    setIntroImage(data.introImage ?? '');
    setContentSections(
      (data.contentSections ?? []).map((s) => ({
        label: asLS(s.label),
        title: asLS(s.title),
        content: asLS(s.content),
        image: s.image ?? '',
        imagePosition: s.imagePosition || 'right',
      }))
    );
    setGalleryImages(data.galleryImages ?? []);
    setCtaTitle(asLS(data.ctaTitle));
    setCtaDescription(asLS(data.ctaDescription));
    setCtaButtonText(asLS(data.ctaButtonText));
    setCtaButtonLink(data.ctaButtonLink ?? '');
  };

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

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSaving(true);
    try {
      const data: Partial<AboutPageData> = {
        heroTitle,
        heroSubtitle,
        heroImage: heroImage || undefined,
        introTitle,
        introContent,
        introImage: introImage || undefined,
        contentSections: contentSections.map((s) => ({
          ...s,
          image: s.image || undefined,
        })),
        galleryImages: galleryImages.filter(Boolean),
        ctaTitle,
        ctaDescription,
        ctaButtonText,
        ctaButtonLink: ctaButtonLink || undefined,
      };
      const updated = await api.updateAboutPage(data);
      loadFromData(updated);
      toast.success('About page saved');
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Failed to save');
    } finally {
      setIsSaving(false);
    }
  };

  const addSection = () =>
    setContentSections([...contentSections, { label: emptyLS(), title: emptyLS(), content: emptyLS(), image: '', imagePosition: 'right' }]);

  const removeSection = (idx: number) =>
    setContentSections(contentSections.filter((_, i) => i !== idx));

  const moveSection = (idx: number, direction: -1 | 1) => {
    const next = [...contentSections];
    const targetIdx = idx + direction;
    if (targetIdx < 0 || targetIdx >= next.length) return;
    [next[idx], next[targetIdx]] = [next[targetIdx], next[idx]];
    setContentSections(next);
  };

  const updateSectionField = (idx: number, field: keyof ContentSection, lang: Lang, value: string) => {
    setContentSections(contentSections.map((s, i) => {
      if (i !== idx) return s;
      const current = s[field];
      if (typeof current === 'object' && current !== null && 'en' in current) {
        return { ...s, [field]: { ...(current as LocalizedString), [lang]: value } };
      }
      return { ...s, [field]: value };
    }));
  };

  const updateSectionString = (idx: number, field: 'image' | 'imagePosition', value: string) => {
    setContentSections(contentSections.map((s, i) => (i === idx ? { ...s, [field]: value } : s)));
  };

  const addGalleryImage = () => setGalleryImages([...galleryImages, '']);
  const removeGalleryImage = (idx: number) => setGalleryImages(galleryImages.filter((_, i) => i !== idx));
  const updateGalleryImage = (idx: number, url: string) =>
    setGalleryImages(galleryImages.map((img, i) => (i === idx ? url : img)));

  if (isLoading) return <PageSpinner />;

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

      <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="Introduction / Mission">
          <Input
            label={`Title (${activeLang.toUpperCase()})`}
            value={introTitle[activeLang]}
            onChange={(e) => updateLS(setIntroTitle, activeLang, e.target.value)}
          />
          <RichTextEditor
            label={`Content (${activeLang.toUpperCase()})`}
            value={introContent[activeLang]}
            onChange={(html) => updateLS(setIntroContent, activeLang, html)}
            minHeight="180px"
            placeholder={activeLang === 'en' ? 'Write the introduction content...' : '輸入介紹內容...'}
          />
          <ImageUploader
            label="Introduction image"
            value={introImage}
            onChange={setIntroImage}
            hint="Image shown beside the introduction text"
          />
        </Section>

        <Section title="Call to Action">
          <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}
          />
          <div className="grid grid-cols-2 gap-3">
            <Input
              label={`Button text (${activeLang.toUpperCase()})`}
              value={ctaButtonText[activeLang]}
              onChange={(e) => updateLS(setCtaButtonText, activeLang, e.target.value)}
            />
            <Input
              label="Button link"
              value={ctaButtonLink}
              onChange={(e) => setCtaButtonLink(e.target.value)}
              placeholder="/golf-id"
            />
          </div>
        </Section>

        <Section title="Gallery Images">
          <p className="text-xs text-gray-500">Upload or paste image URLs. Displayed in a photo grid on the About page.</p>
          <div className="space-y-3">
            {galleryImages.map((url, idx) => (
              <div key={idx} className="flex items-start gap-2">
                <div className="flex-1">
                  <ImageUploader
                    value={url}
                    onChange={(newUrl) => updateGalleryImage(idx, newUrl)}
                    previewHeight="h-24"
                  />
                </div>
                <button type="button" onClick={() => removeGalleryImage(idx)} className="text-gray-400 hover:text-red-500 p-1 mt-1.5">
                  <X size={16} />
                </button>
              </div>
            ))}
          </div>
          <Button type="button" variant="secondary" size="sm" onClick={addGalleryImage}>
            <Plus size={14} />
            Add image
          </Button>
        </Section>
      </div>

      {/* Content Sections — full width */}
      <Section title="Content Sections">
        <p className="text-xs text-gray-500">
          Narrative content blocks shown on the About page with alternating image placement.
        </p>
        <div className="space-y-4">
          {contentSections.map((sec, idx) => (
            <div key={idx} className="border border-gray-200 rounded-lg p-4 relative">
              <div className="absolute top-2 right-2 flex items-center gap-1">
                <button
                  type="button"
                  onClick={() => moveSection(idx, -1)}
                  disabled={idx === 0}
                  className="text-gray-400 hover:text-gray-600 disabled:opacity-30 p-0.5"
                  title="Move up"
                >
                  <ArrowUp size={14} />
                </button>
                <button
                  type="button"
                  onClick={() => moveSection(idx, 1)}
                  disabled={idx === contentSections.length - 1}
                  className="text-gray-400 hover:text-gray-600 disabled:opacity-30 p-0.5"
                  title="Move down"
                >
                  <ArrowDown size={14} />
                </button>
                <button
                  type="button"
                  onClick={() => removeSection(idx)}
                  className="text-gray-400 hover:text-red-500 p-0.5"
                >
                  <X size={16} />
                </button>
              </div>

              <p className="text-xs font-medium text-gray-500 mb-3">Section {idx + 1}</p>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mb-3">
                <Input
                  label={`Label (${activeLang.toUpperCase()})`}
                  value={sec.label[activeLang]}
                  onChange={(e) => updateSectionField(idx, 'label', activeLang, e.target.value)}
                  placeholder={activeLang === 'en' ? 'e.g. Hong Kong Golf Industry Experience' : '例如：香港高爾夫行業經驗'}
                />
                <Input
                  label={`Title (${activeLang.toUpperCase()})`}
                  value={sec.title[activeLang]}
                  onChange={(e) => updateSectionField(idx, 'title', activeLang, e.target.value)}
                  placeholder={activeLang === 'en' ? 'Section heading' : '區段標題'}
                />
              </div>
              <RichTextEditor
                label={`Content (${activeLang.toUpperCase()})`}
                value={sec.content[activeLang]}
                onChange={(html) => updateSectionField(idx, 'content', activeLang, html)}
                minHeight="150px"
                placeholder={activeLang === 'en' ? 'Write section content...' : '輸入區段內容...'}
              />
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mt-3">
                <ImageUploader
                  label="Section image"
                  value={sec.image}
                  onChange={(url) => updateSectionString(idx, 'image', url)}
                  previewHeight="h-32"
                />
                <div className="space-y-1.5">
                  <label className="block text-sm font-medium text-gray-700">Image Position</label>
                  <select
                    value={sec.imagePosition}
                    onChange={(e) => updateSectionString(idx, 'imagePosition', e.target.value)}
                    className="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="left">Left</option>
                    <option value="right">Right</option>
                  </select>
                  <p className="text-xs text-gray-500">On desktop, the image appears on this side of the text.</p>
                </div>
              </div>
            </div>
          ))}
        </div>
        <Button type="button" variant="secondary" size="sm" onClick={addSection}>
          <Plus size={14} />
          Add content section
        </Button>
      </Section>

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