"use client";

import { useEffect, useState } from "react";
import Image from "next/image";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Loader2, Package, X, Check, Box, Tag, FileText, Image as ImageIcon, Edit, ExternalLink } from "lucide-react";
import { getSupabaseClient } from "@/lib/supabase";
import { getCompanyContext } from "@/lib/company-context";
import { buildPublicCatalogUrl } from "@/lib/public-catalog-url";
import Link from "next/link";
import Barcode from "react-barcode";

interface ProductPreviewModalProps {
  productId: string | null;
  onClose: () => void;
}

export function ProductPreviewModal({ productId, onClose }: ProductPreviewModalProps) {
  const [loading, setLoading] = useState(false);
  const [product, setProduct] = useState<any>(null);
  const [selectedImage, setSelectedImage] = useState<string | null>(null);
  const [publicUrl, setPublicUrl] = useState<string | null>(null);

  useEffect(() => {
    if (!productId) {
      setProduct(null);
      setSelectedImage(null);
      setPublicUrl(null);
      return;
    }

    let cancelled = false;

    async function load() {
      setLoading(true);
      const supabase = getSupabaseClient();
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) return;
      
      const ctx = await getCompanyContext(supabase, user);
      const tenantIds = ctx.tenantIds?.length ? ctx.tenantIds : [user.id];
      const [{ data: profilesData }, { data: domainsData }] = await Promise.all([
        supabase.from("profiles").select("id,slug").in("id", tenantIds),
        supabase.from("profile_custom_domains").select("profile_id,domain,verified").in("profile_id", tenantIds),
      ]);

      const { data, error } = await supabase
        .from("products")
        .select(`
          *,
          product_attributes (*),
          product_variations (*),
          product_price_tiers (*),
          product_images (*)
        `)
        .eq("id", productId)
        .in("user_id", tenantIds)
        .single();

      if (!cancelled) {
        if (!error && data) {
          setProduct(data);
          setSelectedImage(data.image_url || null);
        }
        setLoading(false);
      }

      if (!cancelled) {
        const profileSlugValue =
          (profilesData ?? []).find((p) => Boolean((p as { slug?: string | null }).slug)) as
            | { slug?: string | null }
            | undefined;
        const activeDomain = (domainsData ?? []).find(
          (d) => Boolean((d as { verified?: boolean | null }).verified)
        ) as { domain?: string | null; verified?: boolean | null } | undefined;

        const slug = String(profileSlugValue?.slug || "").trim();
        const customDomain = String(activeDomain?.domain || "").trim().toLowerCase();

        if (slug || (customDomain && activeDomain?.verified)) {
          setPublicUrl(
            buildPublicCatalogUrl(window.location.origin, {
              slug,
              custom_domain: customDomain,
              custom_domain_verified: Boolean(activeDomain?.verified),
            }, {
              slugPath: slug ? `/${slug}/p/${productId}` : `/p/${productId}`,
              customPath: `/p/${productId}`,
            })
          );
        } else {
          setPublicUrl(null);
        }
      }
    }

    load();

    return () => {
      cancelled = true;
    };
  }, [productId]);

  if (!productId) return null;

  return (
    <Dialog open={!!productId} onOpenChange={(open) => !open && onClose()}>
      <DialogContent className="max-w-4xl max-h-[90vh] flex flex-col p-0 overflow-hidden gap-0 rounded-2xl bg-slate-50">
        <DialogHeader className="px-6 py-4 border-b border-gray-100 bg-white flex flex-row items-center justify-between shrink-0 relative z-10">
          <DialogTitle className="text-lg font-bold text-slate-800">
            Detalhes do Produto
          </DialogTitle>
          <div className="flex items-center gap-2">
            <a
              href={publicUrl || "#"}
              target={publicUrl ? "_blank" : undefined}
              rel={publicUrl ? "noopener noreferrer" : undefined}
              aria-disabled={!publicUrl}
              onClick={(event) => {
                if (!publicUrl) event.preventDefault();
              }}
              className={`flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm font-bold transition-colors shadow-sm border ${
                publicUrl
                  ? "bg-white border-slate-200 text-slate-700 hover:bg-slate-50"
                  : "bg-slate-100 border-slate-200 text-slate-400 cursor-not-allowed"
              }`}
            >
              <ExternalLink size={14} />
              Ver no Catálogo
            </a>
            <Link 
              href={`/dashboard/products/${productId}`}
              className="flex items-center gap-2 bg-indigo-50 text-indigo-700 hover:bg-indigo-100 px-3 py-1.5 rounded-lg text-sm font-bold transition-colors"
            >
              <Edit size={14} />
              Editar Produto
            </Link>
            <button
              onClick={onClose}
              className="p-2 -mr-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-full transition-colors"
            >
              <X size={18} />
            </button>
          </div>
        </DialogHeader>

        <div className="flex-1 overflow-y-auto p-6">
          {loading ? (
            <div className="flex items-center justify-center h-48">
              <Loader2 className="w-8 h-8 text-indigo-500 animate-spin" />
            </div>
          ) : product ? (
            <div className="space-y-8">
              {/* Header Info */}
              <div className="flex flex-col md:flex-row gap-6">
                <div className="w-full md:w-[240px] shrink-0">
                  <div className="aspect-square rounded-2xl border border-slate-200 overflow-hidden bg-white relative">
                    {selectedImage ? (
                      <Image
                        src={selectedImage}
                        alt={product.name}
                        fill
                        className="object-cover"
                        unoptimized
                      />
                    ) : (
                      <div className="absolute inset-0 flex items-center justify-center text-slate-300">
                        <Package className="w-12 h-12" />
                      </div>
                    )}
                  </div>
                </div>
                
                <div className="flex-1 min-w-0">
                  <h2 className="text-2xl font-bold text-slate-900 tracking-tight">{product.name}</h2>
                  
                  <div className="flex flex-wrap items-center gap-3 mt-3">
                    <div className="px-3 py-1.5 rounded-lg bg-white border border-slate-200 text-lg font-bold text-slate-900 shadow-sm">
                      R$ {(typeof product.price === "number" ? product.price : 0).toFixed(2)}
                    </div>
                    {product.price_on_request && (
                      <div className="px-3 py-1.5 rounded-lg bg-amber-50 text-amber-700 border border-amber-200 text-sm font-semibold">
                        Preço sob consulta
                      </div>
                    )}
                    <div className={`px-3 py-1.5 rounded-lg border text-sm font-semibold flex items-center gap-1.5 ${product.active !== false ? 'bg-emerald-50 text-emerald-700 border-emerald-200' : 'bg-slate-50 text-slate-600 border-slate-200'}`}>
                      <span className={`w-1.5 h-1.5 rounded-full ${product.active !== false ? 'bg-emerald-500' : 'bg-slate-400'}`} />
                      {product.active !== false ? 'Ativo' : 'Inativo'}
                    </div>
                  </div>

                  <div className="flex flex-wrap gap-x-8 gap-y-4 mt-6">
                    <div className="min-w-[80px]">
                      <div className="text-[10px] font-semibold text-slate-500 uppercase tracking-wider mb-1">Estoque</div>
                      <div className="text-sm font-bold text-slate-900">{product.stock || 0} un</div>
                    </div>
                    <div className="min-w-[120px]">
                      <div className="text-[10px] font-semibold text-slate-500 uppercase tracking-wider mb-1">SKU</div>
                      <div className="mt-0.5">
                        <span className="text-slate-700 bg-amber-100/80 px-1.5 py-0.5 rounded text-xs font-bold tracking-wide break-all">
                          {product.sku || '-'}
                        </span>
                      </div>
                    </div>
                    <div className="flex-1 min-w-[160px]">
                      <div className="text-[10px] font-semibold text-slate-500 uppercase tracking-wider mb-1">Cód. Barras</div>
                      <div className="text-sm font-bold text-slate-900 mt-1">
                        {product.barcode ? (
                          <div className="opacity-80 mix-blend-multiply flex flex-col">
                            <div className="h-[28px] overflow-hidden">
                              <Barcode 
                                value={product.barcode} 
                                width={1.5} 
                                height={28} 
                                fontSize={0} 
                                margin={0} 
                                displayValue={false} 
                                background="transparent"
                              />
                            </div>
                            <span className="text-xs font-mono tracking-widest text-slate-600 mt-1">
                              {product.barcode}
                            </span>
                          </div>
                        ) : '-'}
                      </div>
                    </div>
                    <div className="min-w-[80px]">
                      <div className="text-[10px] font-semibold text-slate-500 uppercase tracking-wider mb-1">Venda Mín.</div>
                      <div className="text-sm font-bold text-slate-900">{product.min_sale_qty || 1} un</div>
                    </div>
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                {/* Description */}
                <div className="bg-white p-5 rounded-2xl border border-slate-200">
                  <div className="flex items-center gap-2 mb-4 text-slate-800">
                    <FileText className="w-4 h-4" />
                    <h3 className="font-bold text-sm">Descrição</h3>
                  </div>
                  {product.description ? (
                    <div 
                      className="text-sm text-slate-600 leading-relaxed [&>p]:mb-2 [&>ul]:list-disc [&>ul]:pl-5 [&>ol]:list-decimal [&>ol]:pl-5"
                      dangerouslySetInnerHTML={{ __html: product.description }}
                    />
                  ) : (
                    <div className="text-sm text-slate-600 leading-relaxed whitespace-pre-wrap">
                      <span className="italic text-slate-400">Nenhuma descrição informada.</span>
                    </div>
                  )}
                </div>

                {/* Variations & Attributes */}
                <div className="bg-white p-5 rounded-2xl border border-slate-200">
                  <div className="flex items-center gap-2 mb-4 text-slate-800">
                    <Tag className="w-4 h-4" />
                    <h3 className="font-bold text-sm">Variações e Atributos</h3>
                  </div>
                  
                  {product.product_attributes?.length > 0 ? (
                    <div className="space-y-4">
                      {product.product_attributes.map((attr: any) => (
                        <div key={attr.id}>
                          <div className="text-xs font-semibold text-slate-900 mb-2">{attr.name}</div>
                          <div className="flex flex-wrap gap-2">
                            {/* `options` tem dois formatos no banco: cadastros antigos
                                guardam string pura e os novos guardam objeto
                                ({ id, label, price, stock... }). Renderizar o objeto
                                direto quebrava o modal com "Objects are not valid as
                                a React child". */}
                            {Array.isArray(attr.options) && attr.options.map((opt: unknown, i: number) => {
                              const rotulo =
                                typeof opt === "string"
                                  ? opt
                                  : String((opt as { label?: unknown })?.label ?? "").trim();
                              if (!rotulo) return null;
                              return (
                                <span key={i} className="px-2 py-1 rounded-md bg-slate-100 text-slate-700 text-xs font-medium border border-slate-200">
                                  {rotulo}
                                </span>
                              );
                            })}
                          </div>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <div className="text-sm italic text-slate-400">Nenhum atributo cadastrado.</div>
                  )}

                  {product.product_variations?.length > 0 && (
                    <div className="mt-6">
                      <div className="text-xs font-semibold text-slate-900 mb-2">Variações ({product.product_variations.length})</div>
                      <div className="space-y-2">
                        {product.product_variations.slice(0, 5).map((variation: any) => (
                          <div key={variation.id} className="flex items-center justify-between p-2 rounded-lg bg-slate-50 border border-slate-100 text-xs">
                            <span className="font-medium text-slate-700 truncate">
                              {Object.values(variation.combination || {}).join(' / ')}
                            </span>
                            <div className="flex items-center gap-3 shrink-0">
                              <span className="text-slate-500">Est: {variation.stock || 0}</span>
                            </div>
                          </div>
                        ))}
                        {product.product_variations.length > 5 && (
                          <div className="text-xs text-indigo-600 font-medium text-center pt-1">
                            + {product.product_variations.length - 5} variações...
                          </div>
                        )}
                      </div>
                    </div>
                  )}
                </div>

                {/* Price Tiers */}
                <div className="bg-white p-5 rounded-2xl border border-slate-200">
                  <div className="flex items-center gap-2 mb-4 text-slate-800">
                    <Box className="w-4 h-4" />
                    <h3 className="font-bold text-sm">Regras de Preço (Atacado)</h3>
                  </div>
                  {product.product_price_tiers?.length > 0 ? (
                    <div className="space-y-2">
                      {product.product_price_tiers.sort((a: any, b: any) => (a.min_qty || 0) - (b.min_qty || 0)).map((tier: any) => (
                        <div key={tier.id} className="flex items-center justify-between p-2.5 rounded-lg bg-slate-50 border border-slate-100 text-xs">
                          <span className="font-medium text-slate-700">
                            {tier.min_qty} {tier.max_qty ? `até ${tier.max_qty}` : 'ou mais'} un
                          </span>
                          <span className="font-bold text-emerald-600">
                            R$ {Number(tier.unit_price || 0).toFixed(2)} /un
                          </span>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <div className="text-sm italic text-slate-400">Nenhuma regra de preço por quantidade.</div>
                  )}
                </div>

                {/* Gallery */}
                <div className="bg-white p-5 rounded-2xl border border-slate-200">
                  <div className="flex items-center gap-2 mb-4 text-slate-800">
                    <ImageIcon className="w-4 h-4" />
                    <h3 className="font-bold text-sm">Galeria de Fotos</h3>
                  </div>
                  {product.product_images?.length > 0 ? (
                    <div className="grid grid-cols-3 sm:grid-cols-4 gap-3">
                      {product.product_images.sort((a: any, b: any) => (a.sort_order || 0) - (b.sort_order || 0)).map((img: any) => (
                        <div 
                          key={img.id} 
                          className={`aspect-square rounded-lg border overflow-hidden relative cursor-pointer transition-all ${selectedImage === img.image_url ? 'border-indigo-500 ring-2 ring-indigo-500/20' : 'border-slate-200 hover:border-indigo-300'}`}
                          onClick={() => setSelectedImage(img.image_url)}
                        >
                          <Image src={img.image_url} alt="" fill className="object-cover" unoptimized />
                          {img.is_primary && (
                            <div className="absolute top-1 left-1 bg-indigo-500 text-white text-[9px] font-bold px-1.5 py-0.5 rounded shadow-sm">
                              CAPA
                            </div>
                          )}
                        </div>
                      ))}
                    </div>
                  ) : (
                    <div className="text-sm italic text-slate-400">Nenhuma foto adicional.</div>
                  )}
                </div>

              </div>
            </div>
          ) : (
            <div className="flex flex-col items-center justify-center h-48 text-slate-400">
              <Package className="w-10 h-10 mb-2 opacity-50" />
              <p>Produto não encontrado.</p>
            </div>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}
