import React from 'react';
import { useSelector } from 'react-redux';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { RootState } from '@/store';

interface DDLeadDialogProps {
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
  editingLeadId: string | null;
  leadManagerId: string;
  setLeadManagerId: (id: string) => void;
  leadStatus: 'active' | 'inactive';
  setLeadStatus: (status: 'active' | 'inactive') => void;
  selectedZones: string[];
  setSelectedZones: (zones: string[]) => void;
  onSave: () => void;
  userAssignedData: any[]; // All users to pick from
}

export const DDLeadDialog: React.FC<DDLeadDialogProps> = ({
  isOpen, onOpenChange, editingLeadId, leadManagerId, setLeadManagerId,
  leadStatus, setLeadStatus, selectedZones, setSelectedZones, onSave,
  userAssignedData
}) => {
  const { zones } = useSelector((state: RootState) => state.master);

  // Filter users that have DD-related roles or are already DD-Leads
  const filteredLeadUsers = userAssignedData.filter(u => {
    const roles = u.allRoles || [];
    return roles.some((r: string) => {
      const roleStr = (r || '').toUpperCase();
      return ['DD-ZM', 'ZM', 'ZBH', 'ZONE BUSINESS HEAD', 'DD LEAD', 'DD_LEAD'].includes(roleStr) || 
             roleStr.includes('ZONAL') || roleStr.includes('LEAD');
    });
  });

  const toggleZone = (zoneId: string) => {
    if (selectedZones.includes(zoneId)) {
      setSelectedZones(selectedZones.filter(id => id !== zoneId));
    } else {
      setSelectedZones([...selectedZones, zoneId]);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{editingLeadId ? 'Edit' : 'Add'} DD Lead</DialogTitle>
          <DialogDescription>Assign a user to the DD Lead role and map them to Zones.</DialogDescription>
        </DialogHeader>
        <div className="space-y-4">
          <div className="border-t border-slate-100 pt-4">
            <Label>Select DD Lead User <span className="text-red-500">*</span></Label>
            <Select
              value={leadManagerId}
              onValueChange={(value) => {
                setLeadManagerId(value);
                const selectedUser = userAssignedData.find(u => u.id === value);
                if (selectedUser) {
                  // If they have existing assigned zones
                  if (selectedUser.assignedZoneIds) {
                    setSelectedZones(selectedUser.assignedZoneIds);
                  } else {
                    setSelectedZones([]);
                  }
                }
              }}
              disabled={!!editingLeadId}
            >
              <SelectTrigger className="mt-2 w-full text-slate-900 border-slate-200">
                <SelectValue placeholder="Select User" />
              </SelectTrigger>
              <SelectContent className="max-h-60">
                {filteredLeadUsers.length > 0 ? (
                  filteredLeadUsers.map((user) => (
                    <SelectItem key={user.id} value={user.id}>
                      <div className="flex flex-col text-left">
                        <span className="font-medium text-slate-900">{user.name}</span>
                        <span className="text-xs text-slate-500">{user.email}</span>
                      </div>
                    </SelectItem>
                  ))
                ) : (
                  <div className="p-2 text-sm text-slate-500 text-center">No suitable users found</div>
                )}
              </SelectContent>
            </Select>
          </div>

          <div>
            <Label>Assigned Zones (Review Mapping)</Label>
            <div className="mt-2 border border-slate-200 rounded-lg p-3 max-h-48 overflow-y-auto bg-slate-50/50">
              <div className="grid grid-cols-2 gap-2">
                {zones.map((zone) => (
                  <div key={zone.id} className="flex items-center space-x-2 py-1">
                    <Checkbox
                      id={`lead-zone-${zone.id}`}
                      checked={selectedZones.includes(zone.id)}
                      onCheckedChange={() => toggleZone(zone.id)}
                    />
                    <label htmlFor={`lead-zone-${zone.id}`} className="text-sm cursor-pointer text-slate-700 font-medium">
                      {zone.name}
                    </label>
                  </div>
                ))}
              </div>
            </div>
          </div>

          <div>
            <Label>Status</Label>
            <Select value={leadStatus} onValueChange={(val: 'active' | 'inactive') => setLeadStatus(val)}>
              <SelectTrigger className="mt-2 text-slate-900 border-slate-200">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="active">Active</SelectItem>
                <SelectItem value="inactive">Inactive</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="flex gap-3 pt-6">
            <Button variant="outline" className="flex-1 border-slate-200" onClick={() => onOpenChange(false)}>Cancel</Button>
            <Button className="flex-1 bg-amber-600 hover:bg-amber-700 shadow-sm" onClick={onSave}>Save DD Lead</Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
};
