'use client';

import { useEffect, useState } from 'react';
import { Plus, X, Save, Eye, EyeOff, ShoppingBag } from 'lucide-react';
import toast from 'react-hot-toast';
import api from '@/lib/api';
import { EshopData, EshopProduct, 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();
}

type Tab = 'content' | 'products';

interface ProductItem {
  name: LocalizedString;
  brand: string;
  image: string;
  regularPrice: number;
  memberPrice: number;
  description: LocalizedString;
  isActive: boolean;
}

const emptyProduct = (): ProductItem => ({
  name: emptyLS(),
  brand: '',
  image: '',
  regularPrice: 0,
  memberPrice: 0,
  description: emptyLS(),
  isActive: true,
});

export default function EshopEditorPage() {
  const { activeLang, setActiveLang } = useLanguageTabs();
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [activeTab, setActiveTab] = useState<Tab>('content');

  const [heroTitle, setHeroTitle] = useState<LocalizedString>(emptyLS());
  const [heroSubtitle, setHeroSubtitle] = useState<LocalizedString>(emptyLS());
  const [heroImage, setHeroImage] = useState('');
  const [bannerTitle, setBannerTitle] = useState<LocalizedString>(emptyLS());
  const [bannerDescription, setBannerDescription] = useState<LocalizedString>(emptyLS());
  const [bannerCtaText, setBannerCtaText] = useState<LocalizedString>(emptyLS());
  const [bannerCtaLink, setBannerCtaLink] = useState('');
  const [bannerImage, setBannerImage] = useState('');
  const [hotline, setHotline] = useState('');
  const [products, setProducts] = useState<ProductItem[]>([]);

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

  const loadFromData = (data: EshopData) => {
    setHeroTitle(asLS(data.heroTitle));
    setHeroSubtitle(asLS(data.heroSubtitle));
    setHeroImage(data.heroImage ?? '');
    setBannerTitle(asLS(data.memberBanner?.title));
    setBannerDescription(asLS(data.memberBanner?.description));
    setBannerCtaText(asLS(data.memberBanner?.ctaText));
    setBannerCtaLink(data.memberBanner?.ctaLink ?? '');
    setBannerImage(data.memberBanner?.image ?? '');
    setHotline(data.hotline ?? '');
    setProducts(
      (data.products ?? []).map((p) => ({
        name: asLS(p.name),
        brand: p.brand ?? '',
        image: p.image ?? '',
        regularPrice: p.regularPrice ?? 0,
        memberPrice: p.memberPrice ?? 0,
        description: asLS(p.description),
        isActive: p.isActive ?? true,
      }))
    );
  };

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

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSaving(true);
    try {
      const payload: Partial<EshopData> = {
        heroTitle,
        heroSubtitle,
        heroImage: heroImage || undefined,
        memberBanner: {
          title: bannerTitle,
          description: bannerDescription,
          ctaText: bannerCtaText,
          ctaLink: bannerCtaLink,
          image: bannerImage || undefined,
        },
        hotline,
        products: products.map((p) => ({
          name: p.name,
          brand: p.brand,
          image: p.image || undefined,
          regularPrice: p.regularPrice,
          memberPrice: p.memberPrice,
          description: p.description,
          isActive: p.isActive,
        })),
      };
      const updated = await api.updateEshop(payload);
      loadFromData(updated);
      toast.success('ESHOP page saved');
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Failed to save');
    } finally {
      setIsSaving(false);
    }
  };

  const addProduct = () => setProducts([...products, emptyProduct()]);
  const removeProduct = (idx: number) => setProducts(products.filter((_, i) => i !== idx));
  const toggleProduct = (idx: number) =>
    setProducts(products.map((p, i) => (i === idx ? { ...p, isActive: !p.isActive } : p)));

  const updateProductLS = (idx: number, field: 'name' | 'description', lang: Lang, value: string) =>
    setProducts(
      products.map((p, i) =>
        i === idx ? { ...p, [field]: { ...p[field], [lang]: value } } : p
      )
    );

  const updateProductField = <K extends keyof ProductItem>(idx: number, field: K, value: ProductItem[K]) =>
    setProducts(products.map((p, i) => (i === idx ? { ...p, [field]: value } : p)));

  if (isLoading) return <PageSpinner />;

  const tabs: { id: Tab; label: string }[] = [
    { id: 'content', label: 'Page Content' },
    { id: 'products', label: `Products (${products.length})` },
  ];

  return (
    <div className="space-y-5">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">ESHOP</h1>
          <p className="text-gray-500 mt-1">Manage your online shop products and page content</p>
        </div>
        <Button type="submit" form="eshop-form" isLoading={isSaving}>
          <Save size={16} />
          Save changes
        </Button>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 border-b border-gray-200">
        {tabs.map((tab) => (
          <button
            key={tab.id}
            type="button"
            onClick={() => setActiveTab(tab.id)}
            className={`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors -mb-px ${
              activeTab === tab.id
                ? 'border-blue-600 text-blue-600'
                : 'border-transparent text-gray-500 hover:text-gray-700'
            }`}
          >
            {tab.label}
          </button>
        ))}
      </div>

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

        {activeTab === 'content' && (
          <>
            <Section title="Hero Section">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-4">
                  <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}
                  />
                </div>
                <ImageUploader label="Hero banner image" value={heroImage} onChange={setHeroImage} />
              </div>
            </Section>

            <Section title="Member Banner">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-4">
                  <Input
                    label={`Banner Title (${activeLang.toUpperCase()})`}
                    value={bannerTitle[activeLang]}
                    onChange={(e) => updateLS(setBannerTitle, activeLang, e.target.value)}
                  />
                  <Textarea
                    label={`Banner Description (${activeLang.toUpperCase()})`}
                    value={bannerDescription[activeLang]}
                    onChange={(e) => updateLS(setBannerDescription, activeLang, e.target.value)}
                    rows={3}
                  />
                  <Input
                    label={`CTA Button Text (${activeLang.toUpperCase()})`}
                    value={bannerCtaText[activeLang]}
                    onChange={(e) => updateLS(setBannerCtaText, activeLang, e.target.value)}
                  />
                  <Input
                    label="CTA Link URL"
                    value={bannerCtaLink}
                    onChange={(e) => setBannerCtaLink(e.target.value)}
                    placeholder="https://golfid.com.hk/register"
                  />
                </div>
                <ImageUploader label="Banner image" value={bannerImage} onChange={setBannerImage} />
              </div>
            </Section>

            <Section title="Customer Service">
              <Input
                label="Hotline Number"
                value={hotline}
                onChange={(e) => setHotline(e.target.value)}
                placeholder="(852) 3582 3088"
              />
            </Section>
          </>
        )}

        {activeTab === 'products' && (
          <Section title={`Products (${products.length})`}>
            <div className="space-y-6">
              {products.map((product, idx) => (
                <div
                  key={idx}
                  className={`border rounded-lg p-4 relative transition-colors ${
                    product.isActive ? 'border-gray-200 bg-white' : 'border-gray-200 bg-gray-50 opacity-70'
                  }`}
                >
                  <div className="absolute top-2 right-2 flex items-center gap-2">
                    <button
                      type="button"
                      onClick={() => toggleProduct(idx)}
                      title={product.isActive ? 'Deactivate' : 'Activate'}
                      className={`p-1 rounded transition-colors ${
                        product.isActive ? 'text-green-600 hover:bg-green-50' : 'text-gray-400 hover:bg-gray-100'
                      }`}
                    >
                      {product.isActive ? <Eye size={16} /> : <EyeOff size={16} />}
                    </button>
                    <button
                      type="button"
                      onClick={() => removeProduct(idx)}
                      className="text-gray-400 hover:text-red-500 p-1 rounded transition-colors"
                    >
                      <X size={16} />
                    </button>
                  </div>

                  <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">
                      {product.name.en || product.name.zh || `Product ${idx + 1}`}
                    </span>
                    {!product.isActive && (
                      <span className="text-xs bg-gray-200 text-gray-500 px-2 py-0.5 rounded-full">Hidden</span>
                    )}
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div className="space-y-3 md:col-span-2">
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        <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="Brand"
                          value={product.brand}
                          onChange={(e) => updateProductField(idx, 'brand', e.target.value)}
                          placeholder="e.g. Titleist"
                        />
                      </div>
                      <Textarea
                        label={`Description (${activeLang.toUpperCase()})`}
                        value={product.description[activeLang]}
                        onChange={(e) => updateProductLS(idx, 'description', activeLang, e.target.value)}
                        placeholder={activeLang === 'en' ? 'Optional description' : '選填描述'}
                        rows={2}
                      />
                      <div className="grid grid-cols-2 gap-3">
                        <Input
                          label="Regular Price (HK$)"
                          type="number"
                          min={0}
                          step={0.01}
                          value={product.regularPrice || ''}
                          onChange={(e) => updateProductField(idx, 'regularPrice', parseFloat(e.target.value) || 0)}
                        />
                        <Input
                          label="Member Price (HK$)"
                          type="number"
                          min={0}
                          step={0.01}
                          value={product.memberPrice || ''}
                          onChange={(e) => updateProductField(idx, 'memberPrice', parseFloat(e.target.value) || 0)}
                        />
                      </div>
                    </div>
                    <ImageUploader
                      label="Product image"
                      value={product.image}
                      onChange={(url) => updateProductField(idx, 'image', url)}
                      previewHeight="h-40"
                    />
                  </div>
                </div>
              ))}
            </div>
            <Button type="button" variant="secondary" size="sm" onClick={addProduct} className="mt-4">
              <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>
  );
}
