'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { Plus, Trash2, Save } from 'lucide-react';
import { Input } from '@/components/ui/Input';
import { Textarea } from '@/components/ui/Textarea';
import { Select } from '@/components/ui/Select';
import { Button } from '@/components/ui/Button';
import { Card, CardHeader, CardBody } from '@/components/ui/Card';
import { productsService } from '@/services/products.service';
import { slugify } from '@/utils/slugify';
import type { Product, ProductVariation, Category } from '@/types';

const empty: Partial<Product> = {
  name: '', shortDescription: '', description: '', sku: '', barcode: '',
  categoryId: '', brand: '', images: [], price: 0, promoPrice: undefined,
  cost: undefined, status: 'ativo', featured: false, trackStock: true,
  stock: 0, minStock: 0, tags: [], variations: [], dimensions: {},
};

export function ProductForm({
  storeId,
  categories,
  initial,
}: {
  storeId: string;
  categories: Category[];
  initial?: Product;
}) {
  const router = useRouter();
  const [form, setForm] = useState<Partial<Product>>(initial ?? empty);
  const [imagesText, setImagesText] = useState((initial?.images ?? []).join('\n'));
  const [tagsText, setTagsText] = useState((initial?.tags ?? []).join(', '));
  const [variations, setVariations] = useState<ProductVariation[]>(initial?.variations ?? []);
  const [saving, setSaving] = useState(false);

  function set<K extends keyof Product>(key: K, value: Product[K]) {
    setForm((f) => ({ ...f, [key]: value }));
  }

  function addVariation() {
    setVariations((v) => [
      ...v,
      { id: `var_${Date.now()}`, sku: '', options: { Variação: '' }, stock: 0, active: true },
    ]);
  }
  function updateVariation(id: string, patch: Partial<ProductVariation>) {
    setVariations((v) => v.map((x) => (x.id === id ? { ...x, ...patch } : x)));
  }
  function removeVariation(id: string) {
    setVariations((v) => v.filter((x) => x.id !== id));
  }

  async function handleSave() {
    setSaving(true);
    const images = imagesText.split('\n').map((s) => s.trim()).filter(Boolean);
    const tags = tagsText.split(',').map((s) => s.trim()).filter(Boolean);
    const now = new Date().toISOString();
    const totalVarStock = variations.reduce((s, v) => s + v.stock, 0);

    const product: Product = {
      id: initial?.id ?? `prod_${Date.now()}`,
      storeId,
      name: form.name ?? '',
      slug: slugify(form.name ?? ''),
      shortDescription: form.shortDescription ?? '',
      description: form.description ?? '',
      sku: form.sku ?? '',
      barcode: form.barcode,
      categoryId: form.categoryId ?? '',
      brand: form.brand,
      images: images.length ? images : ['https://images.unsplash.com/photo-1560343090-f0409e92791a?w=800&q=80'],
      price: Number(form.price) || 0,
      promoPrice: form.promoPrice ? Number(form.promoPrice) : undefined,
      cost: form.cost ? Number(form.cost) : undefined,
      status: form.status ?? 'ativo',
      featured: !!form.featured,
      trackStock: !!form.trackStock,
      stock: variations.length ? totalVarStock : Number(form.stock) || 0,
      minStock: Number(form.minStock) || 0,
      dimensions: form.dimensions,
      tags,
      seoTitle: form.seoTitle,
      seoDescription: form.seoDescription,
      variations,
      createdAt: initial?.createdAt ?? now,
      updatedAt: now,
    };

    if (initial) await productsService.update(initial.id, product);
    else await productsService.create(product);
    router.push('/produtos');
  }

  return (
    <div className="grid gap-4 lg:grid-cols-3">
      <div className="space-y-4 lg:col-span-2">
        <Card>
          <CardHeader title="Informações básicas" />
          <CardBody className="space-y-4">
            <Input label="Nome do produto" value={form.name ?? ''} onChange={(e) => set('name', e.target.value)} />
            <Input label="Descrição curta" value={form.shortDescription ?? ''} onChange={(e) => set('shortDescription', e.target.value)} />
            <Textarea label="Descrição completa" rows={4} value={form.description ?? ''} onChange={(e) => set('description', e.target.value)} />
            <div className="grid gap-4 sm:grid-cols-2">
              <Input label="SKU" value={form.sku ?? ''} onChange={(e) => set('sku', e.target.value)} />
              <Input label="Código de barras" value={form.barcode ?? ''} onChange={(e) => set('barcode', e.target.value)} />
            </div>
            <div className="grid gap-4 sm:grid-cols-2">
              <Select label="Categoria" value={form.categoryId ?? ''} onChange={(e) => set('categoryId', e.target.value)}>
                <option value="">Selecione</option>
                {categories.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
              </Select>
              <Input label="Marca" value={form.brand ?? ''} onChange={(e) => set('brand', e.target.value)} />
            </div>
            <Textarea label="Imagens (uma URL por linha)" rows={3} value={imagesText} onChange={(e) => setImagesText(e.target.value)} />
            <Input label="Tags (separadas por vírgula)" value={tagsText} onChange={(e) => setTagsText(e.target.value)} />
          </CardBody>
        </Card>

        <Card>
          <CardHeader title="Variações" action={<Button size="sm" variant="outline" onClick={addVariation}><Plus className="h-4 w-4" /> Adicionar</Button>} />
          <CardBody className="space-y-3">
            {variations.length === 0 && <p className="text-sm text-ink-400">Produto sem variações. Adicione cor, tamanho, etc.</p>}
            {variations.map((v) => {
              const label = Object.values(v.options)[0] ?? '';
              return (
                <div key={v.id} className="grid items-end gap-2 rounded-lg border border-ink-100 p-3 sm:grid-cols-[1fr_1fr_90px_90px_auto]">
                  <Input label="Variação" placeholder="Ex: Cor Azul / Tam M" value={label} onChange={(e) => updateVariation(v.id, { options: { Variação: e.target.value } })} />
                  <Input label="SKU" value={v.sku} onChange={(e) => updateVariation(v.id, { sku: e.target.value })} />
                  <Input label="Preço" type="number" value={v.price ?? ''} onChange={(e) => updateVariation(v.id, { price: e.target.value ? Number(e.target.value) : undefined })} />
                  <Input label="Estoque" type="number" value={v.stock} onChange={(e) => updateVariation(v.id, { stock: Number(e.target.value) })} />
                  <Button size="sm" variant="ghost" onClick={() => removeVariation(v.id)} aria-label="Remover"><Trash2 className="h-4 w-4 text-red-500" /></Button>
                </div>
              );
            })}
          </CardBody>
        </Card>

        <Card>
          <CardHeader title="SEO" />
          <CardBody className="space-y-4">
            <Input label="SEO title" value={form.seoTitle ?? ''} onChange={(e) => set('seoTitle', e.target.value)} />
            <Textarea label="SEO description" rows={2} value={form.seoDescription ?? ''} onChange={(e) => set('seoDescription', e.target.value)} />
          </CardBody>
        </Card>
      </div>

      <div className="space-y-4">
        <Card>
          <CardHeader title="Preço e custo" />
          <CardBody className="space-y-4">
            <Input label="Preço de venda" type="number" value={form.price ?? 0} onChange={(e) => set('price', Number(e.target.value))} />
            <Input label="Preço promocional" type="number" value={form.promoPrice ?? ''} onChange={(e) => set('promoPrice', e.target.value ? Number(e.target.value) : (undefined as never))} />
            <Input label="Custo" type="number" value={form.cost ?? ''} onChange={(e) => set('cost', e.target.value ? Number(e.target.value) : (undefined as never))} />
          </CardBody>
        </Card>

        <Card>
          <CardHeader title="Estoque" />
          <CardBody className="space-y-4">
            <label className="flex items-center gap-2 text-sm text-ink-700">
              <input type="checkbox" checked={!!form.trackStock} onChange={(e) => set('trackStock', e.target.checked)} />
              Controlar estoque
            </label>
            {variations.length === 0 && (
              <Input label="Quantidade em estoque" type="number" value={form.stock ?? 0} onChange={(e) => set('stock', Number(e.target.value))} />
            )}
            <Input label="Estoque mínimo" type="number" value={form.minStock ?? 0} onChange={(e) => set('minStock', Number(e.target.value))} />
          </CardBody>
        </Card>

        <Card>
          <CardHeader title="Dimensões" />
          <CardBody className="grid grid-cols-2 gap-3">
            <Input label="Peso (kg)" type="number" value={form.dimensions?.weight ?? ''} onChange={(e) => set('dimensions', { ...form.dimensions, weight: Number(e.target.value) })} />
            <Input label="Altura (cm)" type="number" value={form.dimensions?.height ?? ''} onChange={(e) => set('dimensions', { ...form.dimensions, height: Number(e.target.value) })} />
            <Input label="Largura (cm)" type="number" value={form.dimensions?.width ?? ''} onChange={(e) => set('dimensions', { ...form.dimensions, width: Number(e.target.value) })} />
            <Input label="Comprimento (cm)" type="number" value={form.dimensions?.length ?? ''} onChange={(e) => set('dimensions', { ...form.dimensions, length: Number(e.target.value) })} />
          </CardBody>
        </Card>

        <Card>
          <CardHeader title="Publicação" />
          <CardBody className="space-y-4">
            <Select label="Status" value={form.status ?? 'ativo'} onChange={(e) => set('status', e.target.value as Product['status'])}>
              <option value="ativo">Ativo</option>
              <option value="inativo">Inativo</option>
            </Select>
            <label className="flex items-center gap-2 text-sm text-ink-700">
              <input type="checkbox" checked={!!form.featured} onChange={(e) => set('featured', e.target.checked)} />
              Produto em destaque
            </label>
            <Button className="w-full" onClick={handleSave} disabled={saving}>
              <Save className="h-4 w-4" /> {saving ? 'Salvando...' : 'Salvar produto'}
            </Button>
          </CardBody>
        </Card>
      </div>
    </div>
  );
}
