import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import { X, Save, Sparkles, ExternalLink, Eye } from 'lucide-react';
import { api } from '../../lib/api-client';
import { Button, Badge, Input, Label, Textarea, Skeleton } from '../../components/ui/primitives';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '../../components/ui/tabs';
import type { ProductDetail, ProductOffer } from './types';

interface Props {
  productId: number;
  onClose: () => void;
  onSaved?: () => void;
}

export function ProductDetailDrawer({ productId, onClose, onSaved }: Props) {
  const qc = useQueryClient();
  const [form, setForm] = useState<Partial<ProductDetail>>({});
  const [previewOpen, setPreviewOpen] = useState(false);

  const { data, isLoading } = useQuery({
    queryKey: ['product', productId],
    queryFn: () => api.get<{ product: ProductDetail; offers: ProductOffer[] }>(`/products/${productId}`),
  });

  useEffect(() => {
    if (data?.product) {
      setForm({
        name: data.product.name,
        display_name: data.product.display_name,
        brand: data.product.brand,
        model_name: data.product.model_name,
        is_sneaker: data.product.is_sneaker,
        gender: data.product.gender,
        description: data.product.description,
        ai_description: data.product.ai_description,
      });
    }
  }, [data?.product]);

  const saveMut = useMutation({
    mutationFn: (body: Partial<ProductDetail>) =>
      api.put<{ product: ProductDetail }>(`/products/${productId}`, body),
    onSuccess: () => {
      toast.success('Product opgeslagen');
      qc.invalidateQueries({ queryKey: ['product', productId] });
      onSaved?.();
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const regenMut = useMutation({
    mutationFn: () => api.post<{ jobId: number }>('/products/bulk', { ids: [productId], action: 'regen-ai-desc' }),
    onSuccess: (res) => toast.success(`AI-desc regeneratie job #${res.jobId}`),
    onError: (e: Error) => toast.error(e.message),
  });

  return (
    <div className="fixed inset-0 z-50 flex" onClick={onClose}>
      <div className="flex-1 bg-black/60 backdrop-blur-sm" />
      <div
        className="w-full max-w-3xl bg-[#141414] border-l border-[#333] flex flex-col overflow-hidden"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between border-b border-[#333] px-6 py-4">
          <div className="flex items-center gap-3 min-w-0">
            {data?.product?.image_url && (
              <img src={data.product.image_url} alt="" className="h-10 w-10 rounded object-cover bg-[#1A1A1A]" />
            )}
            <div className="min-w-0">
              <h2 className="text-sm font-semibold text-[#F5F5F5] truncate">{data?.product?.name ?? 'Laden...'}</h2>
              <p className="text-xs text-[#999]">{data?.product?.brand ?? ''} {data?.product?.model_name ? `· ${data.product.model_name}` : ''}</p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <Button variant="ghost" size="icon" onClick={() => setPreviewOpen(!previewOpen)} title="Live preview">
              <Eye className="h-4 w-4" />
            </Button>
            <Button variant="ghost" size="icon" onClick={onClose}>
              <X className="h-4 w-4" />
            </Button>
          </div>
        </div>

        {isLoading ? (
          <div className="p-6 space-y-3">
            <Skeleton className="h-12 w-full" />
            <Skeleton className="h-48 w-full" />
          </div>
        ) : data?.product ? (
          <div className="flex-1 overflow-hidden flex">
            <div className={`${previewOpen ? 'w-1/2' : 'w-full'} overflow-auto p-6`}>
              <Tabs defaultValue="info">
                <TabsList>
                  <TabsTrigger value="info">Info</TabsTrigger>
                  <TabsTrigger value="desc">Beschrijving</TabsTrigger>
                  <TabsTrigger value="offers">Aanbieders ({data.offers.length})</TabsTrigger>
                </TabsList>

                <TabsContent value="info">
                  <div className="space-y-4">
                    <div>
                      <Label>Naam</Label>
                      <Input className="mt-1" value={form.name ?? ''} onChange={(e) => setForm({ ...form, name: e.target.value })} />
                    </div>
                    <div>
                      <Label>Display naam (override)</Label>
                      <Input className="mt-1" value={form.display_name ?? ''} onChange={(e) => setForm({ ...form, display_name: e.target.value })} />
                    </div>
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <Label>Merk</Label>
                        <Input className="mt-1" value={form.brand ?? ''} onChange={(e) => setForm({ ...form, brand: e.target.value })} />
                      </div>
                      <div>
                        <Label>Model</Label>
                        <Input className="mt-1" value={form.model_name ?? ''} onChange={(e) => setForm({ ...form, model_name: e.target.value })} />
                      </div>
                    </div>
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <Label>Gender</Label>
                        <select
                          className="mt-1 flex h-9 w-full rounded-md border border-[#333] bg-[#0A0A0A] px-3 py-1 text-sm text-[#F5F5F5]"
                          value={form.gender ?? ''}
                          onChange={(e) => setForm({ ...form, gender: e.target.value || null })}
                        >
                          <option value="">—</option>
                          <option value="men">Heren</option>
                          <option value="women">Dames</option>
                          <option value="kids">Kids</option>
                          <option value="unisex">Unisex</option>
                        </select>
                      </div>
                      <div>
                        <Label>Is sneaker</Label>
                        <label className="mt-2 flex items-center gap-2 cursor-pointer">
                          <input
                            type="checkbox"
                            checked={!!form.is_sneaker}
                            onChange={(e) => setForm({ ...form, is_sneaker: e.target.checked })}
                          />
                          <span className="text-sm text-[#F5F5F5]">Toon in catalogus</span>
                        </label>
                      </div>
                    </div>
                    <div className="pt-2 border-t border-[#333] text-xs text-[#666]">
                      ID {data.product.id} · slug <code className="text-[#999]">{data.product.slug}</code>
                    </div>
                  </div>
                </TabsContent>

                <TabsContent value="desc">
                  <div className="space-y-4">
                    <div>
                      <div className="flex items-center justify-between mb-1">
                        <Label>AI-beschrijving</Label>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => regenMut.mutate()}
                          disabled={regenMut.isPending}
                        >
                          <Sparkles className="h-4 w-4" />
                          Regenereer
                        </Button>
                      </div>
                      <Textarea
                        rows={8}
                        value={form.ai_description ?? ''}
                        onChange={(e) => setForm({ ...form, ai_description: e.target.value })}
                        placeholder="Wordt automatisch gegenereerd via Claude Haiku..."
                      />
                    </div>
                    <div>
                      <Label>Handmatige beschrijving (override)</Label>
                      <Textarea
                        rows={5}
                        value={form.description ?? ''}
                        onChange={(e) => setForm({ ...form, description: e.target.value })}
                        placeholder="Leeg laten om AI-versie te gebruiken"
                      />
                    </div>
                  </div>
                </TabsContent>

                <TabsContent value="offers">
                  <div className="space-y-2">
                    {data.offers.length === 0 ? (
                      <p className="text-sm text-[#666]">Geen aanbiedingen gevonden.</p>
                    ) : (
                      data.offers.map((o) => (
                        <div
                          key={o.id}
                          className="flex items-center justify-between px-4 py-3 border border-[#333] rounded-md hover:border-[#444]"
                        >
                          <div className="min-w-0">
                            <p className="text-sm font-medium text-[#F5F5F5]">{o.shop_name ?? o.feed_name}</p>
                            <p className="text-xs text-[#999]">
                              {o.size ? `Maat ${o.size} · ` : ''}
                              {o.color ? `${o.color}` : ''}
                            </p>
                          </div>
                          <div className="flex items-center gap-3">
                            <div className="text-right">
                              <p className="text-sm font-semibold text-[#F5F5F5] tabular-nums">
                                €{Number(o.price).toFixed(2)}
                              </p>
                              {o.in_stock ? (
                                <Badge variant="success">voorraad</Badge>
                              ) : (
                                <Badge variant="muted">uit</Badge>
                              )}
                            </div>
                            <a href={o.product_url} target="_blank" rel="noopener noreferrer">
                              <Button variant="ghost" size="icon">
                                <ExternalLink className="h-4 w-4" />
                              </Button>
                            </a>
                          </div>
                        </div>
                      ))
                    )}
                  </div>
                </TabsContent>
              </Tabs>
            </div>

            {previewOpen && (
              <div className="w-1/2 border-l border-[#333] bg-[#0A0A0A]">
                <iframe
                  src={`/sneakers/${data.product.slug}`}
                  className="w-full h-full"
                  title="Preview"
                  sandbox="allow-same-origin allow-scripts"
                />
              </div>
            )}
          </div>
        ) : (
          <div className="p-6 text-sm text-[#666]">Product niet gevonden.</div>
        )}

        <div className="border-t border-[#333] px-6 py-3 flex items-center justify-between">
          <a
            href={data?.product ? `/sneakers/${data.product.slug}` : '#'}
            target="_blank"
            rel="noopener noreferrer"
            className="text-xs text-[#999] hover:text-[#F5F5F5] flex items-center gap-1"
          >
            <ExternalLink className="h-3 w-3" />
            Open PDP
          </a>
          <div className="flex items-center gap-2">
            <Button variant="ghost" onClick={onClose}>
              Annuleer
            </Button>
            <Button onClick={() => saveMut.mutate(form)} disabled={saveMut.isPending}>
              <Save className="h-4 w-4" />
              Opslaan
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}
