'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 { BonusPointsData, 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 Highlight {
  value: string;
  label: LocalizedString;
}

interface Product {
  brand: LocalizedString;
  name: LocalizedString;
  image: string;
  pointsRequired: string;
}

export default function BonusPointsEditorPage() {
  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 [highlights, setHighlights] = useState<Highlight[]>([]);
  const [ctaTitle, setCtaTitle] = useState<LocalizedString>(emptyLS());
  const [ctaHotline, setCtaHotline] = useState('');
  const [ctaButtonText, setCtaButtonText] = useState<LocalizedString>(emptyLS());
  const [ctaButtonLink, setCtaButtonLink] = useState('');
  const [products, setProducts] = useState<Product[]>([]);

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

  const loadFromData = (data: BonusPointsData) => {
    setHeroTitle(asLS(data.heroTitle));
    setHeroSubtitle(asLS(data.heroSubtitle));
    setHeroImage(data.heroImage ?? '');
    setHighlights(
      (data.highlights ?? []).map((h) => ({
        value: h.value ?? '',
        label: asLS(h.label),
      }))
    );
    setCtaTitle(asLS(data.ctaTitle));
    setCtaHotline(data.ctaHotline ?? '');
    setCtaButtonText(asLS(data.ctaButtonText));
    setCtaButtonLink(data.ctaButtonLink ?? '');
    setProducts(
      (data.products ?? []).map((p) => ({
        brand: asLS(p.brand),
        name: asLS(p.name),
        image: p.image ?? '',
        pointsRequired: p.pointsRequired ?? '',
      }))
    );
  };

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

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSaving(true);
    try {
      const data: Partial<BonusPointsData> = {
        heroTitle,
        heroSubtitle,
        heroImage: heroImage || undefined,
        highlights,
        ctaTitle,
        ctaHotline: ctaHotline || undefined,
        ctaButtonText,
        ctaButtonLink: ctaButtonLink || undefined,
        products,
      };
      const updated = await api.updateBonusPoints(data);
      loadFromData(updated);
      toast.success('Bonus Points page saved');
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Failed to save');
    } finally {
      setIsSaving(false);
    }
  };

  // -- Highlights helpers --
  const addHighlight = () => setHighlights([...highlights, { value: '', label: emptyLS() }]);
  const removeHighlight = (idx: number) => setHighlights(highlights.filter((_, i) => i !== idx));
  const updateHighlightValue = (idx: number, val: string) =>
    setHighlights(highlights.map((h, i) => (i === idx ? { ...h, value: val } : h)));
  const updateHighlightLabel = (idx: number, lang: Lang, val: string) =>
    setHighlights(highlights.map((h, i) => (i === idx ? { ...h, label: { ...h.label, [lang]: val } } : h)));

  // -- Products helpers --
  const addProduct = () =>
    setProducts([...products, { brand: emptyLS(), name: emptyLS(), image: '', pointsRequired: '' }]);
  const removeProduct = (idx: number) => setProducts(products.filter((_, i) => i !== idx));
  const updateProductLS = (idx: number, field: 'brand' | 'name', lang: Lang, value: string) =>
    setProducts(products.map((p, i) => (i === idx ? { ...p, [field]: { ...p[field], [lang]: value } } : p)));
  const updateProductString = (idx: number, field: 'image' | 'pointsRequired', value: string) =>
    setProducts(products.map((p, i) => (i === idx ? { ...p, [field]: value } : p)));

  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">Bonus Points</h1>
        <Button type="submit" form="bonus-points-form" isLoading={isSaving}>
          <Save size={16} />
          Save changes
        </Button>
      </div>

      <form id="bonus-points-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="CTA Footer">
            <Input
              label={`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)} />
            <Input
              label={`CTA button text (${activeLang.toUpperCase()})`}
              value={ctaButtonText[activeLang]}
              onChange={(e) => updateLS(setCtaButtonText, activeLang, e.target.value)}
            />
            <Input
              label="CTA link"
              value={ctaButtonLink}
              onChange={(e) => setCtaButtonLink(e.target.value)}
              placeholder="https://golfcard.com.hk/register"
            />
          </Section>
        </div>

        {/* Stats Highlights */}
        <Section title={`Stats Highlights (${highlights.length})`}>
          <div className="space-y-3">
            {highlights.map((h, idx) => (
              <div key={idx} className="flex items-start gap-3 border border-gray-200 rounded-lg p-3">
                <span className="w-7 h-7 rounded-full bg-primary-600 text-white text-sm font-bold flex items-center justify-center flex-shrink-0 mt-1">
                  {idx + 1}
                </span>
                <div className="flex-1 grid grid-cols-1 sm:grid-cols-2 gap-3">
                  <Input
                    label="Value"
                    value={h.value}
                    onChange={(e) => updateHighlightValue(idx, e.target.value)}
                    placeholder='e.g. "20+"'
                  />
                  <Input
                    label={`Label (${activeLang.toUpperCase()})`}
                    value={h.label[activeLang]}
                    onChange={(e) => updateHighlightLabel(idx, activeLang, e.target.value)}
                    placeholder={activeLang === 'en' ? 'e.g. Products Available' : '例如 可供兌換產品'}
                  />
                </div>
                <button type="button" onClick={() => removeHighlight(idx)} className="text-gray-400 hover:text-red-500 mt-1">
                  <X size={16} />
                </button>
              </div>
            ))}
          </div>
          <Button type="button" variant="secondary" size="sm" onClick={addHighlight}>
            <Plus size={14} />
            Add highlight
          </Button>
        </Section>

        {/* Product Catalog */}
        <Section title={`Product Catalog (${products.length} items)`}>
          <div className="space-y-4">
            {products.map((product, idx) => (
              <div key={idx} className="border border-gray-200 rounded-lg p-4 relative">
                <button
                  type="button"
                  onClick={() => removeProduct(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-primary-600 text-white text-sm font-bold flex items-center justify-center">
                    {idx + 1}
                  </span>
                  <span className="text-sm font-medium text-gray-600">Product {idx + 1}</span>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div className="space-y-3">
                    <Input
                      label={`Brand (${activeLang.toUpperCase()})`}
                      value={product.brand[activeLang]}
                      onChange={(e) => updateProductLS(idx, 'brand', activeLang, e.target.value)}
                      placeholder={activeLang === 'en' ? 'e.g. TaylorMade' : '例如 TaylorMade'}
                    />
                    <Input
                      label={`Product name (${activeLang.toUpperCase()})`}
                      value={product.name[activeLang]}
                      onChange={(e) => updateProductLS(idx, 'name', activeLang, e.target.value)}
                      placeholder={activeLang === 'en' ? 'Product name' : '產品名稱'}
                    />
                    <Input
                      label="Points required"
                      value={product.pointsRequired}
                      onChange={(e) => updateProductString(idx, 'pointsRequired', e.target.value)}
                      placeholder="e.g. 120,000 + HK$450"
                    />
                  </div>
                  <div className="md:col-span-2">
                    <ImageUploader
                      label="Product image"
                      value={product.image}
                      onChange={(url) => updateProductString(idx, 'image', url)}
                      previewHeight="h-36"
                    />
                  </div>
                </div>
              </div>
            ))}
          </div>
          <Button type="button" variant="secondary" size="sm" onClick={addProduct}>
            <Plus size={14} />
            Add product
          </Button>
        </Section>

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