'use client';

import { useState, useRef, useEffect } from 'react';
import { MapPin, X, Check, ChevronRight, Loader2 } from 'lucide-react';

interface RegionInfo {
  code: string;
  name: string;
  supplier_count: number;
  total_pos: number;
}

interface RegionPopoutProps {
  regions: RegionInfo[];
  isLoading?: boolean;
  selectedRegion: string | null;
  onSelect: (region: RegionInfo) => void;
  onClear: () => void;
}

export function RegionPopout({
  regions,
  isLoading = false,
  selectedRegion,
  onSelect,
  onClear,
}: RegionPopoutProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const popoutRef = useRef<HTMLDivElement>(null);

  // Prevent body scroll when modal is open
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = '';
    }
    return () => {
      document.body.style.overflow = '';
    };
  }, [isOpen]);

  // Filter regions based on search query
  const filteredRegions = regions.filter(
    (r) =>
      r.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      r.code.toLowerCase().includes(searchQuery.toLowerCase())
  );

  // Sort regions alphabetically
  const sortedRegions = [...filteredRegions].sort((a, b) =>
    a.name.localeCompare(b.name)
  );

  const handleSelect = (region: RegionInfo) => {
    onSelect(region);
    setIsOpen(false);
    setSearchQuery('');
  };

  const handleClear = () => {
    onClear();
    setIsOpen(false);
    setSearchQuery('');
  };

  const handleClose = () => {
    setIsOpen(false);
    setSearchQuery('');
  };

  return (
    <>
      {/* Trigger Button */}
      <button
        onClick={() => setIsOpen(true)}
        className={`w-full flex items-center justify-between gap-2 px-4 py-3 rounded-xl border text-sm transition-all ${
          selectedRegion
            ? 'border-emerald-300 bg-emerald-50 text-emerald-800'
            : 'border-slate-200 bg-white text-slate-600 hover:border-slate-300'
        }`}
      >
        <div className="flex items-center gap-2 truncate">
          <MapPin className={`h-4 w-4 flex-shrink-0 ${selectedRegion ? 'text-emerald-600' : 'text-slate-400'}`} />
          <span className={selectedRegion ? 'font-medium' : 'text-slate-400'}>
            {selectedRegion || 'Select a region...'}
          </span>
        </div>
        <div className="flex items-center gap-1">
          {selectedRegion && (
            <button
              onClick={(e) => {
                e.stopPropagation();
                onClear();
              }}
              className="p-1 rounded-full hover:bg-emerald-100 text-emerald-600"
              title="Clear region"
            >
              <X className="h-3.5 w-3.5" />
            </button>
          )}
          <ChevronRight
            className={`h-4 w-4 text-slate-400 transition-transform duration-200`}
          />
        </div>
      </button>

      {/* Full Screen Overlay with Blur */}
      {isOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
          {/* Backdrop with blur */}
          <div 
            className="absolute inset-0 bg-slate-900/60 backdrop-blur-md"
            onClick={handleClose}
          />
          
          {/* Modal Content */}
          <div
            ref={popoutRef}
            className="relative w-full max-w-md rounded-2xl border border-slate-200 bg-white shadow-2xl overflow-hidden animate-in fade-in zoom-in-95 duration-200"
          >
            {/* Header */}
            <div className="bg-gradient-to-r from-emerald-600 to-teal-600 px-5 py-4">
              <div className="flex items-center justify-between">
                <h3 className="text-white font-semibold flex items-center gap-2 text-lg">
                  <MapPin className="h-5 w-5" />
                  Select Region
                </h3>
                <button
                  onClick={handleClose}
                  className="p-1.5 rounded-full hover:bg-white/20 text-white/80 hover:text-white transition-colors"
                  title="Close"
                  aria-label="Close region picker"
                >
                  <X className="h-5 w-5" />
                </button>
              </div>
              <p className="text-emerald-100 text-sm mt-1">
                {regions.length} regions available in Ghana
              </p>
            </div>

            {/* Search Input */}
            <div className="p-4 border-b border-slate-100 bg-slate-50">
              <div className="relative">
                <input
                  type="text"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  placeholder="Search regions..."
                  className="w-full pl-4 pr-10 py-2.5 text-sm rounded-xl border border-slate-200 bg-white focus:outline-none focus:ring-2 focus:ring-emerald-500/30 focus:border-emerald-500"
                  autoFocus
                />
                {searchQuery && (
                  <button
                    onClick={() => setSearchQuery('')}
                    className="absolute right-3 top-1/2 -translate-y-1/2 p-1 rounded-full hover:bg-slate-100 text-slate-400"
                    title="Clear search"
                    aria-label="Clear search"
                  >
                    <X className="h-4 w-4" />
                  </button>
                )}
              </div>
            </div>

            {/* Regions List */}
            <div className="max-h-[50vh] overflow-y-auto">
              {isLoading ? (
                <div className="flex items-center justify-center py-12">
                  <Loader2 className="h-6 w-6 animate-spin text-emerald-600" />
                  <span className="ml-2 text-sm text-slate-500">Loading regions...</span>
                </div>
              ) : sortedRegions.length === 0 ? (
                <div className="py-12 text-center">
                  <MapPin className="h-10 w-10 text-slate-300 mx-auto mb-3" />
                  <p className="text-sm text-slate-500 font-medium">No regions found</p>
                  {searchQuery && (
                    <p className="text-xs text-slate-400 mt-1">
                      Try a different search term
                    </p>
                  )}
                </div>
              ) : (
                <div className="p-2">
                  {sortedRegions.map((region) => {
                    const isSelected = selectedRegion === region.name;
                    return (
                      <button
                        key={region.code}
                        onClick={() => handleSelect(region)}
                        className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl text-left transition-all mb-1 last:mb-0 ${
                          isSelected
                            ? 'bg-emerald-100 text-emerald-900 ring-1 ring-emerald-300'
                            : 'hover:bg-slate-50 text-slate-700'
                        }`}
                      >
                        {/* Selection Indicator */}
                        <div
                          className={`flex-shrink-0 w-5 h-5 rounded-full border-2 flex items-center justify-center transition-all ${
                            isSelected
                              ? 'border-emerald-600 bg-emerald-600'
                              : 'border-slate-300'
                          }`}
                        >
                          {isSelected && <Check className="h-3 w-3 text-white" />}
                        </div>

                        {/* Region Info */}
                        <div className="flex-1 min-w-0">
                          <div className="font-medium text-sm truncate">
                            {region.name}
                          </div>
                          <div className="flex items-center gap-2 mt-0.5">
                            <span className="text-xs text-slate-500 font-mono bg-slate-100 px-1.5 py-0.5 rounded">
                              {region.code}
                            </span>
                            {(region.supplier_count > 0 || region.total_pos > 0) && (
                              <>
                                <span className="text-xs text-slate-500">
                                  {region.supplier_count} supplier{region.supplier_count !== 1 ? 's' : ''}
                                </span>
                                {region.total_pos > 0 && (
                                  <>
                                    <span className="text-slate-300">•</span>
                                    <span className="text-xs text-slate-500">
                                      {region.total_pos} PO{region.total_pos !== 1 ? 's' : ''}
                                    </span>
                                  </>
                                )}
                              </>
                            )}
                          </div>
                        </div>

                        {/* Selected checkmark on right */}
                        {isSelected && (
                          <div className="flex-shrink-0 text-emerald-600">
                            <Check className="h-5 w-5" />
                          </div>
                        )}
                      </button>
                    );
                  })}
                </div>
              )}
            </div>

            {/* Footer Actions */}
            <div className="border-t border-slate-100 p-4 bg-slate-50 flex gap-3">
              {selectedRegion && (
                <button
                  onClick={handleClear}
                  className="flex-1 py-2.5 text-sm text-slate-600 hover:text-slate-800 hover:bg-white border border-slate-200 rounded-xl transition-colors font-medium"
                >
                  Clear selection
                </button>
              )}
              <button
                onClick={handleClose}
                className={`${selectedRegion ? 'flex-1' : 'w-full'} py-2.5 text-sm text-white bg-emerald-600 hover:bg-emerald-700 rounded-xl transition-colors font-medium`}
              >
                {selectedRegion ? 'Done' : 'Cancel'}
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
