'use client';

import { useState, useRef, useEffect, useMemo } from 'react';
import Link from 'next/link';
import { 
  Search, 
  School, 
  Package, 
  RefreshCw, 
  Check, 
  X, 
  ChevronDown,
  ChevronRight,
  Building2,
  Clock,
  AlertCircle,
  Database,
  MapPin,
  Wifi,
  WifiOff
} from 'lucide-react';
import { useLiveAllocationFinder, LiveFinderSchool } from '../../hooks/use-live-allocations';
import { useSupplierDirectory } from '../../hooks/use-supplier-directory';

interface LiveAllocationFinderModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSupplierFound?: (supplier: any, school: LiveFinderSchool, commodity: string) => void;
}

// Helper to normalize supplier names for matching
const normalizeForMatch = (name: string): string => 
  (name || '').toUpperCase().replace(/\s+/g, ' ').trim();

export function LiveAllocationFinderModal({ isOpen, onClose, onSupplierFound }: LiveAllocationFinderModalProps) {
  const finder = useLiveAllocationFinder();
  const { suppliers: directorySuppliers } = useSupplierDirectory();
  const schoolInputRef = useRef<HTMLInputElement>(null);
  const schoolContainerRef = useRef<HTMLDivElement>(null);
  const commodityRef = useRef<HTMLDivElement>(null);
  const modalRef = useRef<HTMLDivElement>(null);
  
  // Lock body scroll when modal is open
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
      // Focus the school input when modal opens
      setTimeout(() => schoolInputRef.current?.focus(), 100);
    } else {
      document.body.style.overflow = '';
    }
    return () => {
      document.body.style.overflow = '';
    };
  }, [isOpen]);

  // Close dropdowns when clicking outside
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (schoolContainerRef.current && !schoolContainerRef.current.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]);

  // Handle escape key
  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        if (finder.showSchoolDropdown) {
          finder.setShowSchoolDropdown(false);
        } else if (finder.showCommodityDropdown) {
          finder.setShowCommodityDropdown(false);
        } else {
          onClose();
        }
      }
    };
    
    if (isOpen) {
      document.addEventListener('keydown', handleEscape);
    }
    return () => document.removeEventListener('keydown', handleEscape);
  }, [isOpen, finder.showSchoolDropdown, finder.showCommodityDropdown, onClose, finder]);

  if (!isOpen) return null;

  return (
    <div 
      className="fixed inset-0 z-[100] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4 animate-in fade-in duration-200"
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div 
        ref={modalRef}
        className="relative w-full max-w-lg max-h-[85vh] overflow-hidden rounded-3xl bg-white shadow-2xl animate-in zoom-in-95 duration-200 flex flex-col"
      >
        {/* Header */}
        <div className="sticky top-0 z-20 flex items-center justify-between border-b border-slate-100 bg-gradient-to-r from-emerald-500 to-teal-600 px-5 py-4">
          <div className="flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-white/20">
              <Search className="h-5 w-5 text-white" />
            </div>
            <div>
              <h2 className="text-lg font-bold text-white">Allocation Finder</h2>
              <div className="flex items-center gap-1.5 text-xs text-emerald-100">
                <Wifi className="h-3 w-3" />
                <span>Live API</span>
              </div>
            </div>
          </div>
          <button
            onClick={onClose}
            className="flex h-9 w-9 items-center justify-center rounded-full bg-white/20 text-white transition-colors hover:bg-white/30"
            aria-label="Close modal"
            title="Close"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto px-5 py-5 space-y-5 min-h-[400px]">
          {/* Step 1: School Search */}
          <div className="relative" ref={schoolContainerRef}>
            <label className="mb-2 flex items-center gap-2 text-xs font-semibold text-slate-500 uppercase tracking-wider">
              <span className="flex h-5 w-5 items-center justify-center rounded-full bg-emerald-500 text-[10px] font-bold text-white">1</span>
              Search for School
            </label>
            
            {/* School Input */}
            <div className="relative">
              <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.schoolQuery.length >= 2) {
                    finder.setShowSchoolDropdown(true);
                  }
                }}
                placeholder="Type school name or code (e.g. SCH-0733)..."
                className="w-full rounded-2xl border-2 border-slate-200 bg-slate-50 px-4 py-4 pl-12 text-sm font-medium transition-all placeholder:text-slate-400 focus:border-emerald-400 focus:bg-white focus:outline-none focus:ring-4 focus:ring-emerald-100"
              />
              <School className="absolute left-4 top-1/2 h-5 w-5 -translate-y-1/2 text-slate-400" />
              {finder.selectedSchool && (
                <button
                  onClick={finder.clearSchool}
                  className="absolute right-4 top-1/2 -translate-y-1/2 rounded-full bg-slate-200 p-1 text-slate-500 hover:bg-slate-300"
                  aria-label="Clear school selection"
                  title="Clear selection"
                >
                  <X className="h-4 w-4" />
                </button>
              )}
            </div>
            
            {/* School Dropdown */}
            {finder.showSchoolDropdown && !finder.selectedSchool && (
              <div className="absolute z-50 mt-2 max-h-64 w-full overflow-y-auto rounded-2xl border border-slate-200 bg-white shadow-xl">
                {finder.schoolsLoading ? (
                  <div className="flex items-center gap-3 p-4">
                    <RefreshCw className="h-5 w-5 animate-spin text-emerald-500" />
                    <span className="text-sm text-slate-500">Searching allocations...</span>
                  </div>
                ) : finder.schoolQuery.length < 2 ? (
                  <div className="p-4 text-center text-sm text-slate-400">
                    Type at least 2 characters to search...
                  </div>
                ) : finder.schools.length === 0 ? (
                  <div className="flex flex-col items-center gap-2 p-6">
                    <AlertCircle className="h-8 w-8 text-amber-400" />
                    <span className="text-sm font-medium text-slate-600">No schools found</span>
                    <span className="text-xs text-slate-400">Try a different search term</span>
                  </div>
                ) : (
                  finder.schools.map((school) => (
                    <button
                      key={school.code}
                      onClick={() => finder.selectSchool(school)}
                      className="flex w-full items-center gap-3 px-4 py-3.5 text-left transition-colors hover:bg-emerald-50 first:rounded-t-2xl last:rounded-b-2xl"
                    >
                      <div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-emerald-100">
                        <School className="h-5 w-5 text-emerald-600" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="truncate text-sm font-semibold text-slate-800">{school.name}</div>
                        <div className="flex items-center gap-2 text-xs text-slate-500">
                          <span className="font-mono text-emerald-600">{school.code}</span>
                          <span>•</span>
                          <span className="flex items-center gap-1">
                            <MapPin className="h-3 w-3" />
                            {school.region}
                          </span>
                        </div>
                      </div>
                    </button>
                  ))
                )}
              </div>
            )}
            
            {/* Selected School Badge */}
            {finder.selectedSchool && (
              <div className="mt-3 flex items-center gap-3 rounded-2xl bg-emerald-50 border-2 border-emerald-200 px-4 py-3">
                <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-emerald-500">
                  <Check className="h-5 w-5 text-white" />
                </div>
                <div className="flex-1 min-w-0">
                  <div className="truncate text-sm font-bold text-emerald-800">{finder.selectedSchool.name}</div>
                  <div className="flex items-center gap-2 text-xs text-emerald-600">
                    <span className="font-mono">{finder.selectedSchool.code}</span>
                    <span>•</span>
                    <span>{finder.selectedSchool.region}</span>
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* Step 2: Commodity Selection */}
          {finder.selectedSchool && (
            <div className="relative" ref={commodityRef}>
              <label className="mb-2 flex items-center gap-2 text-xs font-semibold text-slate-500 uppercase tracking-wider">
                <span className="flex h-5 w-5 items-center justify-center rounded-full bg-amber-500 text-[10px] font-bold text-white">2</span>
                Select Commodity
              </label>
              
              {finder.commoditiesLoading ? (
                <div className="flex items-center gap-3 rounded-2xl border-2 border-slate-200 bg-slate-50 px-4 py-4">
                  <RefreshCw className="h-5 w-5 animate-spin text-amber-500" />
                  <span className="text-sm font-medium text-slate-500">Loading commodities...</span>
                </div>
              ) : finder.commodities.length === 0 ? (
                <div className="flex items-center gap-3 rounded-2xl border-2 border-amber-200 bg-amber-50 px-4 py-4">
                  <AlertCircle className="h-5 w-5 text-amber-500" />
                  <span className="text-sm font-medium text-amber-700">No commodities allocated to this school</span>
                </div>
              ) : (
                <>
                  <button
                    onClick={() => finder.setShowCommodityDropdown(!finder.showCommodityDropdown)}
                    className="flex w-full items-center justify-between rounded-2xl border-2 border-slate-200 bg-slate-50 px-4 py-4 text-sm font-medium transition-all hover:border-amber-300 hover:bg-amber-50 focus:border-amber-400 focus:outline-none focus:ring-4 focus:ring-amber-100"
                  >
                    <div className="flex items-center gap-3">
                      <Package className={`h-5 w-5 ${finder.selectedCommodity ? 'text-amber-600' : 'text-slate-400'}`} />
                      <span className={finder.selectedCommodity ? 'text-slate-800' : 'text-slate-400'}>
                        {finder.selectedCommodity || 'Choose a commodity...'}
                      </span>
                    </div>
                    <ChevronDown className={`h-5 w-5 text-slate-400 transition-transform ${finder.showCommodityDropdown ? 'rotate-180' : ''}`} />
                  </button>
                  
                  {/* Commodity Dropdown */}
                  {finder.showCommodityDropdown && (
                    <div className="absolute z-50 mt-2 max-h-56 w-full overflow-y-auto rounded-2xl border border-slate-200 bg-white shadow-xl">
                      {finder.commodities.map((commodity) => (
                        <button
                          key={commodity}
                          onClick={() => finder.selectCommodity(commodity)}
                          className={`flex w-full items-center gap-3 px-4 py-3.5 text-left transition-colors first:rounded-t-2xl last:rounded-b-2xl ${
                            finder.selectedCommodity === commodity 
                              ? 'bg-amber-50' 
                              : 'hover:bg-slate-50'
                          }`}
                        >
                          <Package className={`h-5 w-5 ${finder.selectedCommodity === commodity ? 'text-amber-600' : 'text-slate-400'}`} />
                          <span className={`text-sm font-medium ${finder.selectedCommodity === commodity ? 'text-amber-700' : 'text-slate-700'}`}>
                            {commodity}
                          </span>
                          {finder.selectedCommodity === commodity && (
                            <Check className="ml-auto h-5 w-5 text-amber-600" />
                          )}
                        </button>
                      ))}
                    </div>
                  )}
                </>
              )}
            </div>
          )}

          {/* Step 3: Result */}
          {finder.selectedSchool && finder.selectedCommodity && (
            <div>
              <label className="mb-2 flex items-center gap-2 text-xs font-semibold text-slate-500 uppercase tracking-wider">
                <span className="flex h-5 w-5 items-center justify-center rounded-full bg-blue-500 text-[10px] font-bold text-white">3</span>
                Delivering Supplier
              </label>
              
              {finder.supplierLoading ? (
                <div className="flex flex-col items-center justify-center rounded-2xl border-2 border-slate-200 bg-slate-50 py-10">
                  <RefreshCw className="h-8 w-8 animate-spin text-emerald-500" />
                  <span className="mt-3 text-sm font-medium text-slate-500">Finding supplier...</span>
                </div>
              ) : finder.supplierResult?.found && finder.supplierResult.suppliers?.[0] ? (
                <div className="overflow-hidden rounded-2xl border-2 border-emerald-300 bg-gradient-to-br from-emerald-50 via-teal-50 to-cyan-50">
                  {finder.supplierResult.suppliers.map((supplier, idx) => {
                    const businessName = supplier.business_name || supplier.supplier_name || '';
                    const contactPerson = supplier.supplier_name || '';
                    
                    // Try to find matching supplier in local directory by business_name
                    const normalizedBusinessName = normalizeForMatch(businessName);
                    const matchedDirectorySupplier = directorySuppliers.find(
                      (ds) => normalizeForMatch(ds.name) === normalizedBusinessName
                    );
                    
                    // Use matched directory supplier ID if found, otherwise use allocation API ID
                    const supplierId = matchedDirectorySupplier?.id || supplier.supplier_id || supplier.id || 0;
                    const supplierPhone = matchedDirectorySupplier?.phone || '';
                    
                    // Build href with all relevant info as fallback params
                    const params = new URLSearchParams();
                    params.set('name', businessName);
                    params.set('contact', contactPerson);
                    if (supplierPhone) params.set('phone', supplierPhone);
                    if (supplier.contract_number) params.set('contract', supplier.contract_number);
                    params.set('source', 'live-allocation-finder');
                    
                    const href = `/field-staff/suppliers/${supplierId}?${params.toString()}`;
                    
                    return (
                      <div key={idx} className="p-5">
                        <Link 
                          href={href}
                          onClick={onClose}
                          className="flex items-start gap-4 group"
                        >
                          <div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-gradient-to-br from-emerald-500 to-teal-600 text-white shadow-lg transition-transform group-hover:scale-105">
                            <Building2 className="h-7 w-7" />
                          </div>
                          <div className="flex-1 min-w-0">
                            <div className="text-lg font-bold text-slate-800 group-hover:text-emerald-600 transition-colors flex items-center gap-2">
                              {businessName}
                              <ChevronRight className="h-5 w-5 text-emerald-500 opacity-0 group-hover:opacity-100 transition-opacity" />
                            </div>
                            <div className="text-sm text-slate-600">
                              {contactPerson}
                            </div>
                            <div className={`mt-1 inline-flex items-center rounded-full px-2.5 py-1 text-xs font-bold ${
                              supplier.contract_status === 'ACTIVE' 
                                ? 'bg-emerald-100 text-emerald-700' 
                                : 'bg-amber-100 text-amber-700'
                            }`}>
                              {supplier.contract_status || 'N/A'}
                            </div>
                          </div>
                        </Link>
                      
                        <div className="mt-5 grid grid-cols-2 gap-3">
                          <div className="rounded-xl bg-white/80 px-4 py-3 shadow-sm">
                            <div className="text-[10px] font-semibold text-slate-400 uppercase tracking-wider">Contract</div>
                            <div className="mt-1 font-mono text-sm font-bold text-slate-700">
                              {supplier.contract_number || 'N/A'}
                            </div>
                          </div>
                          <div className="rounded-xl bg-white/80 px-4 py-3 shadow-sm">
                            <div className="text-[10px] font-semibold text-slate-400 uppercase tracking-wider">Quantity</div>
                            <div className="mt-1 text-sm font-bold text-slate-700">
                              {supplier.total_qty?.toLocaleString() || 'N/A'} units
                            </div>
                          </div>
                          <div className="rounded-xl bg-white/80 px-4 py-3 shadow-sm col-span-2">
                            <div className="text-[10px] font-semibold text-slate-400 uppercase tracking-wider">Purchase Order</div>
                            <div className="mt-1 font-mono text-sm font-bold text-emerald-600">
                              {supplier.po_id || 'N/A'}
                            </div>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              ) : (
                <div className="flex flex-col items-center justify-center rounded-2xl border-2 border-amber-200 bg-amber-50 py-10">
                  <div className="flex h-14 w-14 items-center justify-center rounded-full bg-amber-100">
                    <AlertCircle className="h-7 w-7 text-amber-500" />
                  </div>
                  <div className="mt-3 text-sm font-bold text-amber-800">No Supplier Found</div>
                  <div className="mt-1 text-xs text-amber-600 text-center px-6">
                    No allocation exists for this school + commodity combination
                  </div>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        {finder.hasActiveFilters && (
          <div className="sticky bottom-0 border-t border-slate-100 bg-white px-5 py-4">
            <button
              onClick={() => {
                finder.clearAll();
              }}
              className="w-full rounded-2xl border-2 border-slate-200 bg-slate-50 py-3 text-sm font-semibold text-slate-600 transition-all hover:bg-slate-100 active:scale-[0.98]"
            >
              Clear & Start Over
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

export default LiveAllocationFinderModal;
