'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import {
  ProductTemplate,
  loadAllTemplates,
  VARIABLE_TAGS,
} from '@/lib/templates/template-service';
import { PriceMode } from '@/types/catalog';

interface TemplateLibrarySelectorProps {
  selectedTemplateId?: string;
  onSelectTemplate: (template: ProductTemplate) => void;
  currentPriceMode?: PriceMode;
  onPriceModeChange?: (mode: PriceMode) => void;
}

export function TemplateLibrarySelector({
  selectedTemplateId,
  onSelectTemplate,
  currentPriceMode,
  onPriceModeChange,
}: TemplateLibrarySelectorProps) {
  const searchParams = useSearchParams();
  const currentShop = searchParams?.get('shop') || searchParams?.get('shopify_domain') || '';
  const searchStr = searchParams?.toString() ? `?${searchParams.toString()}` : '';
  const templatesHref = searchStr ? `/templates${searchStr}` : (currentShop ? `/templates?shop=${encodeURIComponent(currentShop)}` : '/templates');

  const [templates, setTemplates] = useState<ProductTemplate[]>([]);
  const [activeTemplateId, setActiveTemplateId] = useState<string>(selectedTemplateId || '');

  useEffect(() => {
    const loaded = loadAllTemplates();
    setTemplates(loaded);
    if (!activeTemplateId && loaded.length > 0) {
      // Default to the first template if none is selected
      const initial = loaded.find(t => t.id === selectedTemplateId) || loaded[0];
      setActiveTemplateId(initial.id);
    }

    const handleUpdate = () => {
      setTemplates(loadAllTemplates());
    };

    window.addEventListener('templates_updated', handleUpdate);
    window.addEventListener('storage', handleUpdate);
    return () => {
      window.removeEventListener('templates_updated', handleUpdate);
      window.removeEventListener('storage', handleUpdate);
    };
  }, [selectedTemplateId]);

  const handleTemplateClick = (t: ProductTemplate) => {
    setActiveTemplateId(t.id);
    onSelectTemplate(t);
    if (onPriceModeChange && t.priceRule) {
      onPriceModeChange(t.priceRule);
    }
  };

  const activeTemplate = templates.find(t => t.id === activeTemplateId) || templates[0];

  const renderPreviewTitle = () => {
    let t = activeTemplate?.titlePattern || '{{product.title}} - {{variant.title}} | {{product.vendor}}';
    VARIABLE_TAGS.forEach(v => {
      t = t.replaceAll(v.tag, v.sample);
    });
    return t;
  };

  const renderPreviewDescription = () => {
    let d = activeTemplate?.descriptionPattern || '{{product.description}} Available in multiple sizes and colors. Fast worldwide shipping.';
    VARIABLE_TAGS.forEach(v => {
      d = d.replaceAll(v.tag, v.sample);
    });
    return d;
  };

  return (
    <div className="bg-white border border-slate-200/80 rounded-2xl p-5 sm:p-6 shadow-xs space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between flex-wrap gap-2">
        <div className="flex items-center gap-2">
          <div className="w-6 h-6 rounded-lg bg-theme/10 text-theme flex items-center justify-center font-bold">
            <i className="fa-solid fa-wand-magic-sparkles text-xs" />
          </div>
          <div>
            <h3 className="text-xs font-bold text-slate-900 uppercase tracking-wider">
              Template Library ({templates.length})
            </h3>
            <p className="text-[11px] text-slate-500">
              Select dynamic title, pricing rules, and custom labels for this catalog
            </p>
          </div>
        </div>

        <Link
          href={templatesHref}
          className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-slate-50 hover:bg-slate-100 text-slate-700 text-xs font-semibold border border-slate-200/80 transition shadow-2xs"
          title="Open Product Templates in Shopify Admin"
        >
          <i className="fa-solid fa-sliders text-xs text-theme" />
          <span>Manage in Template Studio</span>
          <i className="fa-solid fa-arrow-right text-[10px] text-slate-400" />
        </Link>
      </div>

      {/* Grid of All Templates in Library */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
        {templates.map(tpl => {
          const isSelected = activeTemplateId === tpl.id;
          return (
            <div
              key={tpl.id}
              onClick={() => handleTemplateClick(tpl)}
              className={`p-3.5 rounded-xl border text-left cursor-pointer transition-all relative flex flex-col justify-between ${
                isSelected
                  ? 'border-theme bg-theme/5 shadow-2xs ring-2 ring-theme/20'
                  : 'border-slate-200/80 bg-white hover:bg-slate-50 text-slate-700'
              }`}
            >
              <div className="w-full">
                <div className="flex items-start justify-between gap-2 mb-2">
                  <h4 className="font-bold text-xs text-slate-900 leading-snug">
                    {tpl.name}
                  </h4>
                  {tpl.badgeText ? (
                    <span className="shrink-0 px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wider bg-slate-100 text-slate-700 border border-slate-200">
                      {tpl.badgeText}
                    </span>
                  ) : tpl.isDefault ? (
                    <span className="shrink-0 px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wider bg-theme/10 text-theme border border-theme/20">
                      Default
                    </span>
                  ) : (
                    <span className="shrink-0 px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wider bg-purple-50 text-purple-700 border border-purple-200">
                      Custom
                    </span>
                  )}
                </div>

                <p className="text-[11px] text-slate-500 leading-relaxed">
                  {tpl.description}
                </p>
              </div>

              <div className="mt-3 pt-2.5 border-t border-slate-100 flex items-center justify-between text-[11px]">
                <span className="font-mono text-slate-600 text-[10px] truncate max-w-[170px]">
                  {tpl.priceRule === 'compare_at_and_price'
                    ? '🏷️ Sale & Compare Price'
                    : tpl.priceRule === 'compare_at_only'
                    ? '🏷️ MSRP / Compare Price'
                    : '🏷️ Price Only'}
                </span>
                {isSelected ? (
                  <span className="inline-flex items-center gap-1 text-[11px] font-bold text-theme">
                    <i className="fa-solid fa-check text-xs" /> Applied
                  </span>
                ) : (
                  <span className="text-[10px] font-semibold text-slate-400 hover:text-slate-600">
                    Click to Apply
                  </span>
                )}
              </div>
            </div>
          );
        })}
      </div>

      {/* Live Meta Ad Preview Card (matching Template Studio) */}
      {activeTemplate && (
        <div className="pt-2">
          <div className="bg-white rounded-2xl border border-slate-200/80 p-4 sm:p-5 shadow-xs space-y-4 max-w-md mx-auto">
            {/* Header */}
            <div className="flex items-center justify-between pb-3 border-b border-slate-100">
              <div className="flex items-center gap-2">
                <i className="fa-regular fa-eye text-theme text-sm" />
                <h3 className="text-xs font-bold text-slate-900 uppercase tracking-wider">
                  Live Meta Ad Preview
                </h3>
              </div>
              <span className="px-2 py-0.5 rounded-full text-[10px] font-semibold bg-emerald-50 text-emerald-700 border border-emerald-200">
                Advantage+ Feed
              </span>
            </div>

            {/* Simulated Facebook Carousel Ad Card */}
            <div className="bg-slate-50 border border-slate-200 rounded-2xl overflow-hidden shadow-sm">
              {/* Ad Sponsor Header */}
              <div className="p-3 sm:p-3.5 bg-white flex items-center gap-2.5 border-b border-slate-100">
                <div className="w-7 h-7 rounded-full bg-blue-600 text-white font-bold text-xs flex items-center justify-center shrink-0">
                  f
                </div>
                <div className="min-w-0">
                  <h5 className="font-bold text-xs text-slate-900 leading-none truncate">
                    {currentShop || 'Your Shopify Store'}
                  </h5>
                  <p className="text-[10px] text-slate-400 mt-0.5 truncate">Sponsored • Advantage+ Catalog Ad</p>
                </div>
              </div>

              {/* Product Image Box */}
              <div className="relative aspect-square bg-slate-100 flex items-center justify-center overflow-hidden">
                <img
                  src="https://images.unsplash.com/photo-1551698618-1dfe5d97d256?auto=format&fit=crop&w=600&q=80"
                  alt="Sample Product"
                  width={600}
                  height={600}
                  loading="lazy"
                  className="w-full h-full object-cover"
                />
                {/* Dynamic Sale Badge Overlay */}
                {activeTemplate.priceRule === 'compare_at_and_price' && (
                  <div className="absolute top-3 left-3 bg-rose-600 text-white text-[11px] font-extrabold px-2.5 py-1 rounded-lg shadow-md uppercase tracking-wider flex items-center gap-1">
                    <span>SALE -29%</span>
                  </div>
                )}
                <div className="absolute bottom-3 right-3 bg-slate-900/80 backdrop-blur-xs text-white text-[10px] font-medium px-2 py-0.5 rounded-md">
                  1 of 6 Variants
                </div>
              </div>

              {/* Ad Body Content */}
              <div className="p-3.5 sm:p-4 bg-white space-y-2">
                <div className="flex items-baseline justify-between gap-2">
                  <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider truncate">
                    {(currentShop || 'quickstart.myshopify.com').toUpperCase()}
                  </span>
                  <div className="flex items-center gap-1.5 shrink-0">
                    {activeTemplate.priceRule === 'compare_at_and_price' ? (
                      <>
                        <span className="text-xs line-through text-slate-400 font-medium">$349.00</span>
                        <span className="text-sm font-extrabold text-slate-900">$249.00 USD</span>
                      </>
                    ) : (
                      <span className="text-sm font-extrabold text-slate-900">$249.00 USD</span>
                    )}
                  </div>
                </div>

                {/* Rendered Live Title */}
                <h4 className="font-bold text-xs text-slate-900 leading-snug line-clamp-2">
                  {renderPreviewTitle()}
                </h4>

                {/* Rendered Live Description */}
                <p className="text-[11px] text-slate-500 line-clamp-2 leading-relaxed">
                  {renderPreviewDescription()}
                </p>

                <button
                  type="button"
                  className="w-full mt-2 py-2 px-3 bg-slate-100 hover:bg-slate-200 text-slate-900 rounded-xl text-xs font-bold transition flex items-center justify-center gap-1.5 cursor-pointer"
                >
                  <span>Shop Now</span>
                  <i className="fa-solid fa-arrow-right text-xs" />
                </button>
              </div>
            </div>

            {/* Feed Meta Tags Preview */}
            <div className="p-3 bg-slate-50 rounded-xl border border-slate-200/80 space-y-1.5 text-xs">
              <div className="font-bold text-slate-900 text-[11px]">Exported Catalog Payload:</div>
              <div className="font-mono text-[10px] text-slate-600 space-y-1 overflow-x-auto">
                <div className="truncate"><strong>title:</strong> {renderPreviewTitle()}</div>
                <div><strong>price:</strong> {activeTemplate.priceRule === 'compare_at_and_price' ? '349.00 USD' : '249.00 USD'}</div>
                {activeTemplate.priceRule === 'compare_at_and_price' && (
                  <div><strong>sale_price:</strong> 249.00 USD</div>
                )}
                {activeTemplate.customLabels?.label0 && (
                  <div className="truncate"><strong>custom_label_0:</strong> {activeTemplate.customLabels.label0}</div>
                )}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
