'use client';

import React, { useState, useEffect } from 'react';
import { useSearchParams } from 'next/navigation';
import { ShopifyCollection } from '@/lib/shopify/product-service';
import { apiUrl } from '@/lib/utils/asset';

interface CollectionPickerModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSelect: (selectedCollections: ShopifyCollection[]) => void;
  initiallySelectedIds?: string[];
  shop?: string;
}

export function CollectionPickerModal({
  isOpen,
  onClose,
  onSelect,
  initiallySelectedIds = [],
  shop,
}: CollectionPickerModalProps) {
  const searchParams = useSearchParams();
  const currentShop = shop || searchParams?.get('shop') || searchParams?.get('shopify_domain') || '';

  const getEndpoint = (path: string) => {
    const qs = currentShop ? `shop=${encodeURIComponent(currentShop)}` : '';
    const sep = path.includes('?') ? '&' : '?';
    return apiUrl(qs ? `${path}${sep}${qs}` : path);
  };

  const [searchQuery, setSearchQuery] = useState('');
  const [collections, setCollections] = useState<ShopifyCollection[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedMap, setSelectedMap] = useState<Record<string, ShopifyCollection>>({});

  useEffect(() => {
    if (isOpen) {
      fetchCollections();
    }
  }, [isOpen]);

  const fetchCollections = async () => {
    setLoading(true);
    try {
      const res = await fetch(getEndpoint('/api/shopify/collections'));
      const data = await res.json();
      if (data.success) {
        const loaded: ShopifyCollection[] = data.collections || [];
        setCollections(loaded);
        const initialMap: Record<string, ShopifyCollection> = {};
        loaded.forEach(c => {
          if (initiallySelectedIds.includes(String(c.id))) {
            initialMap[String(c.id)] = c;
          }
        });
        setSelectedMap(initialMap);
      }
    } catch (err) {
      console.error('Failed to fetch collections', err);
    } finally {
      setLoading(false);
    }
  };

  const toggleSelect = (col: ShopifyCollection) => {
    const id = String(col.id);
    setSelectedMap(prev => {
      const next = { ...prev };
      if (next[id]) {
        delete next[id];
      } else {
        next[id] = col;
      }
      return next;
    });
  };

  const handleConfirm = () => {
    onSelect(Object.values(selectedMap));
    onClose();
  };

  if (!isOpen) return null;

  const filtered = collections.filter(c =>
    c.title.toLowerCase().includes(searchQuery.toLowerCase())
  );
  const selectedCount = Object.keys(selectedMap).length;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-xs p-3 sm:p-4 animate-in fade-in-50 duration-200">
      <div className="bg-white border border-slate-200 rounded-2xl w-full max-w-xl shadow-xl overflow-hidden flex flex-col max-h-[85vh]">
        <div className="px-4 sm:px-6 py-3.5 sm:py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50/70">
          <div>
            <div className="flex items-center gap-2">
              <h3 className="text-base font-bold text-slate-900">Select Collections</h3>
              <span className="px-2 py-0.5 rounded-full text-[10px] font-semibold bg-emerald-50 text-emerald-700 border border-emerald-200">
                Live Shopify Sync
              </span>
            </div>
            <p className="text-xs text-slate-500 mt-0.5">Filter products synced by Shopify collection</p>
          </div>
          <div className="flex items-center gap-2">
            <button
              type="button"
              onClick={() => fetchCollections()}
              disabled={loading}
              title="Refresh collections from Shopify"
              className="text-slate-400 hover:text-slate-700 rounded-lg p-1.5 hover:bg-slate-200/60 transition disabled:opacity-50"
            >
              <i className={`fa-solid fa-arrows-rotate text-sm ${loading ? 'fa-spin' : ''}`} />
            </button>
            <button onClick={onClose} className="text-slate-400 hover:text-slate-700 rounded-lg p-1.5 hover:bg-slate-200/60">
              <i className="fa-solid fa-xmark text-base" />
            </button>
          </div>
        </div>

        <div className="p-3.5 sm:p-4 bg-white border-b border-slate-100">
          <div className="relative">
            <i className="fa-solid fa-magnifying-glass text-slate-400 absolute left-3 top-1/2 -translate-y-1/2 text-xs" />
            <input
              type="text"
              value={searchQuery}
              onChange={e => setSearchQuery(e.target.value)}
              placeholder="Search collections by title..."
              className="w-full pl-9 pr-3 py-2 bg-white border border-slate-200 rounded-xl text-xs text-slate-900 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme"
            />
          </div>
        </div>

        <div className="flex-1 overflow-y-auto min-h-[250px] p-3 sm:p-4 space-y-2">
          {loading ? (
            <div className="flex items-center justify-center h-48 text-slate-400 text-xs gap-2">
              <i className="fa-solid fa-spinner fa-spin text-theme text-sm" />
              <span>Loading collections...</span>
            </div>
          ) : filtered.length === 0 ? (
            <div className="flex items-center justify-center h-48 text-slate-400 text-xs">No collections found</div>
          ) : (
            filtered.map(col => {
              const isSelected = !!selectedMap[String(col.id)];
              return (
                <div
                  key={col.id}
                  onClick={() => toggleSelect(col)}
                  className={`flex items-center justify-between p-3 rounded-xl border cursor-pointer transition ${
                    isSelected
                      ? 'bg-theme/5 border-theme text-theme shadow-2xs ring-1 ring-theme/20'
                      : 'bg-white border-slate-200 text-slate-700 hover:bg-slate-50'
                  }`}
                >
                  <div className="flex items-center gap-3">
                    <input
                      type="checkbox"
                      checked={isSelected}
                      onChange={() => toggleSelect(col)}
                      className="w-4 h-4 rounded border-slate-300 text-theme focus:ring-theme"
                    />
                    <div>
                      <p className="text-xs font-bold text-slate-900">{col.title}</p>
                      <p className="text-[11px] text-slate-400">ID: {col.id} • {col.products_count ?? 0} products</p>
                    </div>
                  </div>
                </div>
              );
            })
          )}
        </div>

        <div className="px-4 sm:px-6 py-3 sm:py-4 border-t border-slate-100 bg-slate-50/70 flex flex-col-reverse sm:flex-row sm:items-center justify-between gap-3">
          <span className="text-xs text-slate-500 font-medium">{selectedCount} collections selected</span>
          <div className="flex items-center justify-end gap-2">
            <button
              onClick={onClose}
              className="px-4 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-200/60 rounded-xl"
            >
              Cancel
            </button>
            <button
              onClick={handleConfirm}
              className="px-5 py-2 text-xs font-bold bg-theme hover:bg-theme-hover text-white rounded-xl shadow-sm hover:shadow-md transition active:scale-95"
            >
              Add {selectedCount > 0 ? `(${selectedCount})` : ''} collections
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
