'use client';

import { useState, useRef, useEffect } from 'react';
import { 
  Search, 
  School, 
  Package, 
  RefreshCw, 
  Check, 
  X, 
  Zap, 
  ChevronDown,
  Building2,
  Clock,
  AlertCircle,
  Sparkles,
  Database,
  FileText,
  TrendingUp
} from 'lucide-react';
import { useSmartFinder, SmartFinderSchool } from '../../hooks/use-smart-finder';

interface SmartFinderPanelProps {
  onSupplierFound?: (supplier: any, school: SmartFinderSchool, commodity: string) => void;
  className?: string;
}

export function SmartFinderPanel({ onSupplierFound, className = '' }: SmartFinderPanelProps) {
  const finder = useSmartFinder();
  const schoolInputRef = useRef<HTMLInputElement>(null);
  const commodityRef = useRef<HTMLDivElement>(null);
  
  // Close dropdowns when clicking outside
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (schoolInputRef.current && !schoolInputRef.current.parentElement?.contains(e.target as Node)) {
        finder.setShowSchoolDropdown(false);
      }
      if (commodityRef.current && !commodityRef.current.contains(e.target as Node)) {
        finder.setShowCommodityDropdown(false);
      }
    };
    
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [finder]);
  
  // Notify parent when supplier is found
  useEffect(() => {
    if (finder.hasResult && finder.supplierResult?.suppliers?.[0] && finder.selectedSchool && finder.selectedCommodity) {
      onSupplierFound?.(
        finder.supplierResult.suppliers[0],
        finder.selectedSchool,
        finder.selectedCommodity
      );
    }
  }, [finder.hasResult, finder.supplierResult, finder.selectedSchool, finder.selectedCommodity, onSupplierFound]);

  return (
    <div className={`space-y-4 ${className}`}>
      {/* Header with Sync Button */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2 text-sm font-medium text-slate-700">
          <Zap className="h-4 w-4 text-amber-500" />
          <span>Smart Allocation Finder</span>
          {finder.queryTime !== null && (
            <span className="ml-2 rounded-full bg-emerald-100 px-2 py-0.5 text-xs text-emerald-700">
              {finder.queryTime < 1 ? '<1' : finder.queryTime.toFixed(1)}ms
            </span>
          )}
        </div>
        
        <button
          onClick={() => finder.syncCache()}
          disabled={finder.isSyncing}
          className="flex items-center gap-1.5 rounded-lg bg-slate-100 px-3 py-1.5 text-xs font-medium text-slate-600 transition-all hover:bg-slate-200 disabled:opacity-50"
          title="Sync cache with latest allocations"
        >
          <RefreshCw className={`h-3.5 w-3.5 ${finder.isSyncing ? 'animate-spin' : ''}`} />
          {finder.isSyncing ? 'Syncing...' : 'Sync'}
        </button>
      </div>

      {/* Cache Status Bar */}
      {finder.cacheStatus && (
        <div className="flex items-center gap-3 rounded-lg bg-gradient-to-r from-slate-50 to-slate-100 px-3 py-2 text-xs">
          <div className="flex items-center gap-1.5">
            <Database className={`h-3.5 w-3.5 ${finder.cacheValid ? 'text-emerald-500' : 'text-amber-500'}`} />
            <span className="text-slate-600">
              {finder.cacheStatus.record_count.toLocaleString()} allocations
            </span>
          </div>
          <span className="text-slate-300">|</span>
          <div className="flex items-center gap-1.5">
            <School className="h-3.5 w-3.5 text-blue-500" />
            <span className="text-slate-600">{finder.cacheStatus.school_count} schools</span>
          </div>
          <span className="text-slate-300">|</span>
          <div className="flex items-center gap-1.5">
            <Clock className="h-3.5 w-3.5 text-slate-400" />
            <span className="text-slate-500">
              {finder.cacheStatus.last_sync_formatted 
                ? `Synced ${new Date(finder.cacheStatus.last_sync! * 1000).toLocaleTimeString()}`
                : 'Not synced'}
            </span>
          </div>
        </div>
      )}

      {/* School Search */}
      <div className="relative">
        <label className="mb-1.5 block text-xs font-medium text-slate-500 uppercase tracking-wide">
          Step 1: Select School
        </label>
        <div className="relative">
          <School className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
          <input
            ref={schoolInputRef}
            type="text"
            value={finder.schoolQuery}
            onChange={(e) => {
              finder.setSchoolQuery(e.target.value);
              if (!finder.selectedSchool) {
                finder.setShowSchoolDropdown(true);
              }
            }}
            onFocus={() => {
              if (!finder.selectedSchool) {
                finder.setShowSchoolDropdown(true);
              }
            }}
            placeholder="Search by school name or code..."
            className="w-full rounded-xl border border-slate-200 bg-white py-3 pl-10 pr-10 text-sm transition-all focus:border-emerald-400 focus:outline-none focus:ring-2 focus:ring-emerald-100"
          />
          {finder.selectedSchool ? (
            <button
              onClick={finder.clearSchool}
              className="absolute right-3 top-1/2 -translate-y-1/2 rounded-full p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-600"
              title="Clear school selection"
              aria-label="Clear school selection"
            >
              <X className="h-4 w-4" />
            </button>
          ) : finder.schoolsLoading ? (
            <RefreshCw className="absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 animate-spin text-slate-400" />
          ) : null}
        </div>
        
        {/* School Dropdown */}
        {finder.showSchoolDropdown && !finder.selectedSchool && finder.schools.length > 0 && (
          <div className="absolute z-50 mt-1 max-h-64 w-full overflow-y-auto rounded-xl border border-slate-200 bg-white shadow-lg">
            {finder.schools.map((school) => (
              <button
                key={school.code}
                onClick={() => finder.selectSchool(school)}
                className="flex w-full items-start gap-3 px-4 py-3 text-left transition-colors hover:bg-emerald-50"
              >
                <School className="mt-0.5 h-4 w-4 flex-shrink-0 text-emerald-600" />
                <div className="min-w-0 flex-1">
                  <div className="truncate text-sm font-medium text-slate-700">{school.name}</div>
                  <div className="flex items-center gap-2 text-xs text-slate-500">
                    <span className="font-mono">{school.code}</span>
                    <span>•</span>
                    <span>{school.region}</span>
                  </div>
                </div>
              </button>
            ))}
          </div>
        )}
        
        {/* Selected School Badge */}
        {finder.selectedSchool && (
          <div className="mt-2 flex items-center gap-2 rounded-lg bg-emerald-50 px-3 py-2">
            <Check className="h-4 w-4 text-emerald-600" />
            <div className="flex-1 min-w-0">
              <div className="truncate text-sm font-medium text-emerald-700">{finder.selectedSchool.name}</div>
              <div className="text-xs text-emerald-600">{finder.selectedSchool.code} • {finder.selectedSchool.region}</div>
            </div>
          </div>
        )}
      </div>

      {/* Commodity Selection - Only show when school is selected */}
      {finder.selectedSchool && (
        <div className="relative" ref={commodityRef}>
          <label className="mb-1.5 block text-xs font-medium text-slate-500 uppercase tracking-wide">
            Step 2: Select Commodity
          </label>
          
          {finder.commoditiesLoading ? (
            <div className="flex items-center gap-2 rounded-xl border border-slate-200 bg-slate-50 px-4 py-3">
              <RefreshCw className="h-4 w-4 animate-spin text-slate-400" />
              <span className="text-sm text-slate-500">Loading commodities...</span>
            </div>
          ) : finder.commodities.length === 0 ? (
            <div className="flex items-center gap-2 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3">
              <AlertCircle className="h-4 w-4 text-amber-500" />
              <span className="text-sm text-amber-700">No commodities found for this school</span>
            </div>
          ) : (
            <>
              <button
                onClick={() => finder.setShowCommodityDropdown(!finder.showCommodityDropdown)}
                className="flex w-full items-center justify-between rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm transition-all hover:border-emerald-400 focus:border-emerald-400 focus:outline-none focus:ring-2 focus:ring-emerald-100"
              >
                <div className="flex items-center gap-2">
                  <Package className="h-4 w-4 text-slate-400" />
                  <span className={finder.selectedCommodity ? 'text-slate-700' : 'text-slate-400'}>
                    {finder.selectedCommodity || 'Select a commodity...'}
                  </span>
                </div>
                <ChevronDown className={`h-4 w-4 text-slate-400 transition-transform ${finder.showCommodityDropdown ? 'rotate-180' : ''}`} />
              </button>
              
              {/* Commodity Dropdown */}
              {finder.showCommodityDropdown && (
                <div className="absolute z-50 mt-1 max-h-64 w-full overflow-y-auto rounded-xl border border-slate-200 bg-white shadow-lg">
                  {finder.commodities.map((commodity) => (
                    <button
                      key={commodity}
                      onClick={() => finder.selectCommodity(commodity)}
                      className={`flex w-full items-center gap-3 px-4 py-3 text-left transition-colors hover:bg-emerald-50 ${
                        finder.selectedCommodity === commodity ? 'bg-emerald-50' : ''
                      }`}
                    >
                      <Package className={`h-4 w-4 ${finder.selectedCommodity === commodity ? 'text-emerald-600' : 'text-slate-400'}`} />
                      <span className={`text-sm ${finder.selectedCommodity === commodity ? 'font-medium text-emerald-700' : 'text-slate-700'}`}>
                        {commodity}
                      </span>
                      {finder.selectedCommodity === commodity && (
                        <Check className="ml-auto h-4 w-4 text-emerald-600" />
                      )}
                    </button>
                  ))}
                </div>
              )}
              
              {/* Selected Commodity Badge */}
              {finder.selectedCommodity && !finder.showCommodityDropdown && (
                <div className="mt-2 flex items-center gap-2">
                  <button
                    onClick={finder.clearCommodity}
                    className="flex items-center gap-1.5 rounded-full bg-emerald-100 px-3 py-1 text-xs font-medium text-emerald-700 hover:bg-emerald-200"
                  >
                    <Package className="h-3 w-3" />
                    {finder.selectedCommodity}
                    <X className="h-3 w-3" />
                  </button>
                </div>
              )}
            </>
          )}
        </div>
      )}

      {/* Result Card */}
      {finder.selectedSchool && finder.selectedCommodity && (
        <div className="space-y-3">
          <label className="block text-xs font-medium text-slate-500 uppercase tracking-wide">
            🎯 Delivering Supplier
          </label>
          
          {finder.supplierLoading ? (
            <div className="flex items-center justify-center rounded-xl border border-slate-200 bg-slate-50 py-8">
              <RefreshCw className="h-6 w-6 animate-spin text-emerald-500" />
            </div>
          ) : finder.supplierResult?.found && finder.supplierResult.suppliers?.[0] ? (
            <div className="overflow-hidden rounded-xl border border-emerald-200 bg-gradient-to-br from-emerald-50 to-teal-50">
              {finder.supplierResult.suppliers.map((supplier, idx) => (
                <div key={idx} className="p-4">
                  <div className="flex items-start gap-3">
                    <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-emerald-500 text-white">
                      <Building2 className="h-5 w-5" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="text-lg font-semibold text-slate-800">
                        {supplier.business_name || supplier.supplier_name || supplier.name}
                      </div>
                      <div className="text-sm text-slate-600">
                        {supplier.supplier_name || supplier.name}
                      </div>
                    </div>
                    <div className={`rounded-full px-2.5 py-1 text-xs font-medium ${
                      supplier.contract_status === 'ACTIVE' 
                        ? 'bg-emerald-100 text-emerald-700' 
                        : 'bg-amber-100 text-amber-700'
                    }`}>
                      {supplier.contract_status || 'N/A'}
                    </div>
                  </div>
                  
                  <div className="mt-4 grid grid-cols-2 gap-3">
                    <div className="rounded-lg bg-white/60 px-3 py-2">
                      <div className="text-xs text-slate-500">Contract #</div>
                      <div className="font-mono text-sm font-medium text-slate-700">
                        {supplier.contract_number || 'N/A'}
                      </div>
                    </div>
                    <div className="rounded-lg bg-white/60 px-3 py-2">
                      <div className="text-xs text-slate-500">Allocated Qty</div>
                      <div className="text-sm font-medium text-slate-700">
                        {supplier.total_qty?.toLocaleString() || 'N/A'} units
                      </div>
                    </div>
                    <div className="col-span-2 rounded-lg bg-white/60 px-3 py-2">
                      <div className="text-xs text-slate-500">Total Value</div>
                      <div className="text-lg font-bold text-emerald-600">
                        GHS {supplier.total_value?.toLocaleString(undefined, { minimumFractionDigits: 2 }) || 'N/A'}
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="flex flex-col items-center justify-center rounded-xl border border-amber-200 bg-amber-50 py-8">
              <AlertCircle className="h-8 w-8 text-amber-400" />
              <div className="mt-2 text-sm font-medium text-amber-700">No supplier found</div>
              <div className="text-xs text-amber-600">
                No allocation exists for this school + commodity combination
              </div>
            </div>
          )}
        </div>
      )}

      {/* Clear All Button */}
      {finder.hasActiveFilters && (
        <button
          onClick={finder.clearAll}
          className="flex w-full items-center justify-center gap-2 rounded-xl border border-slate-200 bg-white py-2.5 text-sm font-medium text-slate-600 transition-all hover:bg-slate-50"
        >
          <X className="h-4 w-4" />
          Clear All Filters
        </button>
      )}
    </div>
  );
}
