'use client';

import React, { useMemo } from 'react';
import { Building, MapPin, Layers, Home, Filter, ShieldCheck, ChevronRight } from 'lucide-react';
import { ScopeType, StateItem, LgaItem, WardItem, PollingUnitItem } from '@/types';
import {
  NIGERIAN_STATES,
  LGAS_BY_STATE,
  WARDS_BY_LGA,
  POLLING_UNITS_BY_WARD
} from '@/lib/electoralData';

interface CascadingDelimitationSelectorProps {
  userScopeType?: ScopeType;
  userScopeId?: string;
  selectedStateId?: string | null;
  selectedLgaId?: string | null;
  selectedWardId?: string | null;
  selectedPuCode?: string | null;
  onStateChange?: (state: StateItem | null) => void;
  onLgaChange?: (lga: LgaItem | null) => void;
  onWardChange?: (ward: WardItem | null) => void;
  onPuChange?: (pu: PollingUnitItem | null) => void;
  className?: string;
}

export const CascadingDelimitationSelector: React.FC<CascadingDelimitationSelectorProps> = ({
  userScopeType = 'NATIONAL',
  userScopeId = 'ALL',
  selectedStateId,
  selectedLgaId,
  selectedWardId,
  selectedPuCode,
  onStateChange,
  onLgaChange,
  onWardChange,
  onPuChange,
  className = '',
}) => {
  // Compute default selected state, lga, ward
  const activeStateId = useMemo(() => {
    if (selectedStateId) return selectedStateId;
    if (userScopeType === 'STATE') return userScopeId;
    if (userScopeType === 'LGA' || userScopeType === 'WARD' || userScopeType === 'PU') return userScopeId.slice(0, 2);
    if (userScopeType === 'REGION') {
      const zStates = NIGERIAN_STATES.filter(s => s.geopolitical_zone === userScopeId);
      return zStates.length > 0 ? zStates[0].id : '24';
    }
    return '24'; // Default Lagos
  }, [selectedStateId, userScopeType, userScopeId]);

  const activeLgaId = useMemo(() => {
    if (selectedLgaId) return selectedLgaId;
    if (userScopeType === 'LGA') return userScopeId;
    if (userScopeType === 'WARD' || userScopeType === 'PU') return userScopeId.slice(0, 5);
    const lgas = LGAS_BY_STATE[activeStateId] || [];
    return lgas.length > 0 ? lgas[0].id : '';
  }, [selectedLgaId, userScopeType, userScopeId, activeStateId]);

  const activeWardId = useMemo(() => {
    if (selectedWardId) return selectedWardId;
    if (userScopeType === 'WARD') return userScopeId;
    if (userScopeType === 'PU') return userScopeId.slice(0, 8);
    const wards = WARDS_BY_LGA[activeLgaId] || [];
    return wards.length > 0 ? wards[0].id : '';
  }, [selectedWardId, userScopeType, userScopeId, activeLgaId]);

  const activePuCode = useMemo(() => {
    if (selectedPuCode) return selectedPuCode;
    if (userScopeType === 'PU') return userScopeId;
    const pus = POLLING_UNITS_BY_WARD[activeWardId] || [];
    return pus.length > 0 ? pus[0].pu_code : '';
  }, [selectedPuCode, userScopeType, userScopeId, activeWardId]);

  // Available lists based on cascading selections
  const availableStates = useMemo(() => {
    if (userScopeType === 'STATE') {
      return NIGERIAN_STATES.filter(s => s.id === userScopeId);
    }
    if (userScopeType === 'LGA' || userScopeType === 'WARD' || userScopeType === 'PU') {
      const stateId = userScopeId.slice(0, 2);
      return NIGERIAN_STATES.filter(s => s.id === stateId);
    }
    if (userScopeType === 'REGION') {
      return NIGERIAN_STATES.filter(s => s.geopolitical_zone === userScopeId);
    }
    return NIGERIAN_STATES;
  }, [userScopeType, userScopeId]);

  const availableLgas = useMemo(() => {
    const list = LGAS_BY_STATE[activeStateId] || [];
    if (userScopeType === 'LGA') {
      return list.filter(l => l.id === userScopeId);
    }
    if (userScopeType === 'WARD' || userScopeType === 'PU') {
      const lgaId = userScopeId.slice(0, 5);
      return list.filter(l => l.id === lgaId);
    }
    return list;
  }, [activeStateId, userScopeType, userScopeId]);

  const availableWards = useMemo(() => {
    const list = WARDS_BY_LGA[activeLgaId] || [];
    if (userScopeType === 'WARD') {
      return list.filter(w => w.id === userScopeId);
    }
    if (userScopeType === 'PU') {
      const wardId = userScopeId.slice(0, 8);
      return list.filter(w => w.id === wardId);
    }
    return list;
  }, [activeLgaId, userScopeType, userScopeId]);

  const availablePus = useMemo(() => {
    const list = POLLING_UNITS_BY_WARD[activeWardId] || [];
    if (userScopeType === 'PU') {
      return list.filter(p => p.pu_code === userScopeId);
    }
    return list;
  }, [activeWardId, userScopeType, userScopeId]);

  // Lock flags based on RBAC
  const isStateLocked = userScopeType === 'STATE' || userScopeType === 'LGA' || userScopeType === 'WARD' || userScopeType === 'PU';
  const isLgaLocked = userScopeType === 'LGA' || userScopeType === 'WARD' || userScopeType === 'PU';
  const isWardLocked = userScopeType === 'WARD' || userScopeType === 'PU';
  const isPuLocked = userScopeType === 'PU';

  // Handlers
  const handleSelectState = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const stId = e.target.value;
    const stObj = NIGERIAN_STATES.find(s => s.id === stId) || null;
    if (onStateChange) onStateChange(stObj);

    // Cascading reset
    const newLgas = LGAS_BY_STATE[stId] || [];
    if (newLgas.length > 0) {
      if (onLgaChange) onLgaChange(newLgas[0]);
      const newWards = WARDS_BY_LGA[newLgas[0].id] || [];
      if (newWards.length > 0) {
        if (onWardChange) onWardChange(newWards[0]);
        const newPus = POLLING_UNITS_BY_WARD[newWards[0].id] || [];
        if (newPus.length > 0 && onPuChange) onPuChange(newPus[0]);
      }
    }
  };

  const handleSelectLga = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const lgId = e.target.value;
    const lgas = LGAS_BY_STATE[activeStateId] || [];
    const lgObj = lgas.find(l => l.id === lgId) || null;
    if (onLgaChange) onLgaChange(lgObj);

    const newWards = WARDS_BY_LGA[lgId] || [];
    if (newWards.length > 0) {
      if (onWardChange) onWardChange(newWards[0]);
      const newPus = POLLING_UNITS_BY_WARD[newWards[0].id] || [];
      if (newPus.length > 0 && onPuChange) onPuChange(newPus[0]);
    }
  };

  const handleSelectWard = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const wdId = e.target.value;
    const wards = WARDS_BY_LGA[activeLgaId] || [];
    const wdObj = wards.find(w => w.id === wdId) || null;
    if (onWardChange) onWardChange(wdObj);

    const newPus = POLLING_UNITS_BY_WARD[wdId] || [];
    if (newPus.length > 0 && onPuChange) onPuChange(newPus[0]);
  };

  const handleSelectPu = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const pCode = e.target.value;
    const pus = POLLING_UNITS_BY_WARD[activeWardId] || [];
    const puObj = pus.find(p => p.pu_code === pCode) || null;
    if (onPuChange) onPuChange(puObj);
  };

  return (
    <div className={`bg-gradient-to-r from-slate-900 via-slate-950 to-emerald-950 border border-slate-800 rounded-2xl p-4 shadow-xl ${className}`}>
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 mb-3">
        <div className="flex items-center gap-2">
          <div className="p-2 bg-emerald-500/10 border border-emerald-500/30 rounded-xl text-emerald-400">
            <Filter className="w-4 h-4" />
          </div>
          <div>
            <h4 className="text-xs font-black text-white uppercase tracking-wider flex items-center gap-1.5 flex-wrap">
              Official INEC Cascading Delimitation Selector
              <span className="text-[9px] px-2 py-0.5 rounded-full bg-emerald-950 text-emerald-300 border border-emerald-700/60 font-mono">
                State &rarr; LGA &rarr; Ward &rarr; PU
              </span>
            </h4>
            <p className="text-[11px] text-slate-400">
              Filter situation room monitoring and collation by official INEC names &amp; codes.
            </p>
          </div>
        </div>

        {userScopeType !== 'NATIONAL' && (
          <div className="flex items-center gap-1.5 px-2.5 py-1 rounded-xl bg-amber-950/60 border border-amber-600/40 text-amber-300 text-[10px] font-bold shrink-0">
            <ShieldCheck className="w-3.5 h-3.5 text-amber-400 shrink-0" />
            <span>Jurisdiction Scope Locked: {userScopeType}</span>
          </div>
        )}
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
        {/* 1. STATE DROPDOWN */}
        <div className="space-y-1">
          <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider flex items-center gap-1">
            <Home className="w-3 h-3 text-emerald-400" />
            <span>1. State (INEC Code)</span>
          </label>
          <select
            value={activeStateId}
            onChange={handleSelectState}
            disabled={isStateLocked}
            className="w-full py-2 px-3 bg-slate-950 border border-slate-800 rounded-xl text-xs font-bold text-emerald-300 focus:outline-none focus:border-amber-400 disabled:opacity-75 disabled:bg-slate-900"
          >
            {availableStates.map(s => (
              <option key={s.id} value={s.id}>
                [{s.id}] {s.name} State
              </option>
            ))}
          </select>
        </div>

        {/* 2. LGA DROPDOWN */}
        <div className="space-y-1">
          <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider flex items-center gap-1">
            <Building className="w-3 h-3 text-emerald-400" />
            <span>2. LGA (INEC Code)</span>
          </label>
          <select
            value={activeLgaId}
            onChange={handleSelectLga}
            disabled={isLgaLocked || availableLgas.length === 0}
            className="w-full py-2 px-3 bg-slate-950 border border-slate-800 rounded-xl text-xs font-bold text-white focus:outline-none focus:border-amber-400 disabled:opacity-75 disabled:bg-slate-900"
          >
            {availableLgas.map(l => (
              <option key={l.id} value={l.id}>
                [{l.id}] {l.name} LGA
              </option>
            ))}
          </select>
        </div>

        {/* 3. WARD DROPDOWN */}
        <div className="space-y-1">
          <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider flex items-center gap-1">
            <Layers className="w-3 h-3 text-purple-400" />
            <span>3. Ward (Registration Area)</span>
          </label>
          <select
            value={activeWardId}
            onChange={handleSelectWard}
            disabled={isWardLocked || availableWards.length === 0}
            className="w-full py-2 px-3 bg-slate-950 border border-slate-800 rounded-xl text-xs font-bold text-purple-300 focus:outline-none focus:border-amber-400 disabled:opacity-75 disabled:bg-slate-900"
          >
            {availableWards.map(w => (
              <option key={w.id} value={w.id}>
                [{w.id}] {w.name} Ward
              </option>
            ))}
          </select>
        </div>

        {/* 4. POLLING UNIT DROPDOWN */}
        <div className="space-y-1">
          <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider flex items-center gap-1">
            <MapPin className="w-3 h-3 text-amber-400" />
            <span>4. Polling Unit (INEC Registered Name & Code)</span>
          </label>
          <select
            value={activePuCode}
            onChange={handleSelectPu}
            disabled={isPuLocked || availablePus.length === 0}
            className="w-full py-2 px-3 bg-slate-950 border border-slate-800 rounded-xl text-xs font-bold text-amber-300 focus:outline-none focus:border-amber-400 disabled:opacity-75 disabled:bg-slate-900 truncate"
          >
            {availablePus.map(p => (
              <option key={p.pu_code} value={p.pu_code}>
                {p.pu_name} [{p.pu_code}]
              </option>
            ))}
          </select>
        </div>
      </div>
    </div>
  );
};
