'use client';

import React, { useState } from 'react';
import { Layers, Plus, Trash2, UserCheck } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Modal } from '@/components/ui/modal';
import { useBulkAssign } from '@/services/district-sector-assignments/queries';
import { useAllDistrictSectors, useAllSectors } from '@/services/sectors/queries';
import { useSystemUSerRoles } from '@/services/roles/queries';

interface BulkAssignModalProps {
  userId: string;
  userFullName: string;
  districtsList: Array<{ id: string; name: string }>;
  onClose: () => void;
}

interface AssignmentPair {
  districtId: string;
  sectorId: string;
  assignedApproverId: string;
}

function DynamicSectorSelectRow({
  districtId,
  selectedSectorId,
  onChange,
  disabledSectorIds,
}: {
  districtId: string;
  selectedSectorId: string;
  onChange: (sectorId: string) => void;
  disabledSectorIds: string[];
}) {
  const { data: sectorsData, isLoading: isLoadingSectors } = useAllDistrictSectors(districtId, 'inactive');
  const sectors = (sectorsData as any)?.items || sectorsData || [];

  console.log("ALL SECTOR IN BULK:", sectors)

  return (
    <div className="w-full">
      <select
        value={selectedSectorId}
        onChange={(e) => onChange(e.target.value)}
        className="w-full text-xs p-1.5 border border-border/40 rounded-md bg-background text-foreground focus:outline-none focus:border-primary cursor-pointer"
        disabled={!districtId || sectors.length === 0}
        required
      >
        <option value="">
          {!districtId 
            ? '-- Select District First --' 
            : isLoadingSectors 
              ? 'Loading associated targets...' 
              : sectors.length === 0 
                ? 'No functional sectors mapped' 
                : '-- Choose Sector --'}
        </option>
        {sectors.map((s: any) => {
          // Fallback safely whether the object is a flat Sector or nested DistrictSector
          const targetSectorId = s.sectorId || s.sector?.id || s.id;
          const targetSectorName = s.sector?.name || s.name || 'Unnamed Sector';
          const targetSectorCode = s.sector?.code || s.code;

          const isTaken = disabledSectorIds.includes(targetSectorId) && targetSectorId !== selectedSectorId;
          return (
            <option key={s.id || targetSectorId} value={targetSectorId} disabled={isTaken}>
              {targetSectorName} {targetSectorCode ? `(${targetSectorCode})` : ''} {s.isActive ? '(Active)' : '(Unassigned)'} {isTaken ? ' - Selected' : ''}
            </option>
          );
        })}
      </select>
    </div>
  );
}

export default function BulkAssignModal({ userId, userFullName, districtsList, onClose }: BulkAssignModalProps) {
  const { data: systemRoles } = useSystemUSerRoles();
  const approversList = (systemRoles as any)?.items || systemRoles || [];

  const [selectedPairs, setSelectedPairs] = useState<AssignmentPair[]>([
    { districtId: '', sectorId: '', assignedApproverId: '' }
  ]);
  const [error, setError] = useState<string | null>(null);
  const bulkMutation = useBulkAssign();

  const addPairRow = () => {
    setSelectedPairs([...selectedPairs, { districtId: '', sectorId: '', assignedApproverId: '' }]);
  };

  const removePairRow = (index: number) => {
    setSelectedPairs(selectedPairs.filter((_, i) => i !== index));
  };

  const handleUpdate = (index: number, field: keyof AssignmentPair, value: string) => {
    const updated = [...selectedPairs];
    if (updated[index]) {
      updated[index][field] = value;
      if (field === 'districtId') {
        updated[index]['sectorId'] = ''; 
      }
      setSelectedPairs(updated);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    const validPairs = selectedPairs.filter(p => p.districtId && p.sectorId);
    if (validPairs.length === 0) {
      setError('At least one fully qualified parameters row is required.');
      return;
    }

    try {
      await bulkMutation.mutateAsync({
        userId,
        assignments: validPairs.map(p => ({
          districtId: p.districtId,
          sectorId: p.sectorId,
          ...(p.assignedApproverId && { assignedApproverId: p.assignedApproverId }),
        }))
      });
      onClose();
    } catch (err: any) {
      setError(err?.response?.data?.message || 'Error compiling database insertions.');
    }
  };

  return (
    <Modal onClose={onClose} icon={Layers} iconClassName="text-indigo-500" title={`Bulk Assign Matrices: ${userFullName}`}>
      <form onSubmit={handleSubmit} className="p-4 space-y-4">
        {error && (
          <div className="p-2 bg-destructive/5 border border-destructive/20 text-destructive text-[10px] rounded-lg">
            {error}
          </div>
        )}

        <div className="space-y-3 max-h-80 overflow-y-auto pr-1">
          {selectedPairs.map((pair, index) => {
            const takenSectorsForDistrict = selectedPairs
              .filter((p, idx) => idx !== index && p.districtId === pair.districtId)
              .map(p => p.sectorId);

            return (
              <div key={index} className="space-y-2 bg-muted/30 p-2.5 rounded-lg border border-border/20">
                <div className="flex items-center gap-2">
                  {/* DISTRICT SELECTOR */}
                  <div className="w-1/2">
                    <label className="text-[9px] font-bold uppercase text-muted-foreground block mb-1">
                      District Jurisdiction
                    </label>
                    <select
                      value={pair.districtId}
                      onChange={(e) => handleUpdate(index, 'districtId', e.target.value)}
                      className="w-full text-xs p-1.5 border border-border/40 rounded-md bg-background text-foreground focus:outline-none focus:border-primary cursor-pointer"
                      required
                    >
                      <option value="">-- Choose District --</option>
                      {districtsList?.map(d => <option key={d.id} value={d.id}>{d.name}</option>)}
                    </select>
                  </div>

                  {/* SECTOR SELECTOR */}
                  <div className="w-1/2">
                    <label className="text-[9px] font-bold uppercase text-muted-foreground block mb-1">
                      Target Sector
                    </label>
                    <DynamicSectorSelectRow 
                      districtId={pair.districtId}
                      selectedSectorId={pair.sectorId}
                      disabledSectorIds={takenSectorsForDistrict}
                      onChange={(value) => handleUpdate(index, 'sectorId', value)}
                    />
                  </div>

                  {selectedPairs.length > 1 && (
                    <button 
                      type="button" 
                      onClick={() => removePairRow(index)} 
                      className="text-muted-foreground/60 hover:text-destructive p-1 cursor-pointer self-end mb-1"
                      title="Remove Row"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  )}
                </div>

                {/* KYC APPROVER SELECTOR DROPDOWN */}
                <div className="pt-1 border-t border-border/10">
                  <label className="text-[9px] font-bold uppercase text-muted-foreground flex items-center gap-1 mb-1">
                    <UserCheck className="h-3 w-3 text-indigo-500" />
                    <span>Designated Sector KYC Approver (Optional)</span>
                  </label>
                  <select
                    value={pair.assignedApproverId}
                    onChange={(e) => handleUpdate(index, 'assignedApproverId', e.target.value)}
                    className="w-full text-xs p-1.5 border border-border/40 rounded-md bg-background text-foreground focus:outline-none focus:border-primary cursor-pointer"
                  >
                    <option value="">-- Auto-Assign (District Owner / Admin) --</option>
                    {approversList?.map((u: any) => (
                      <option key={u.id} value={u.id}>
                        {u.firstName} {u.lastName} ({u.role}) - {u.email}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
            );
          })}
        </div>

        <Button type="button" variant="outline" onClick={addPairRow} className="h-7 text-[10px] gap-1 font-bold border-dashed w-full">
          <Plus className="h-3 w-3" /> Add Matrix Row
        </Button>

        <div className="flex items-center justify-end gap-2 border-t border-border/10 pt-3">
          <Button type="button" variant="ghost" onClick={onClose} className="h-8 text-xs">Cancel</Button>
          <Button type="submit" disabled={bulkMutation.isPending} className="h-8 text-xs bg-indigo-500 hover:bg-indigo-600 text-white">
            {bulkMutation.isPending ? 'Writing Records...' : 'Execute Assignments'}
          </Button>
        </div>
      </form>
    </Modal>
  );
}