import React from 'react';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';

interface ZoneDialogProps {
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
  editingZoneId: string | null;
  zoneName: string;
  setZoneName: (name: string) => void;
  zoneCode: string;
  setZoneCode: (code: string) => void;
  zoneDescription: string;
  setZoneDescription: (desc: string) => void;
  zonalBusinessHeadId: string;
  setZonalBusinessHeadId: (id: string) => void;
  userAssignedData: any[];
  onSave: () => void;
}

export const ZoneDialog: React.FC<ZoneDialogProps> = ({
    isOpen, onOpenChange, editingZoneId, zoneName, setZoneName, 
    zoneCode, setZoneCode, zoneDescription, setZoneDescription, 
    zonalBusinessHeadId, setZonalBusinessHeadId, userAssignedData, onSave
}) => {
    const filteredZBHUsers = (userAssignedData || []).filter((u: any) => {
        // Always include the currently assigned head to ensure pre-filling works
        if (zonalBusinessHeadId !== 'none' && u.id === zonalBusinessHeadId) return true;

        const roles = (u.allRoles || []).map((r: string) => String(r || '').toUpperCase());
        const topLevelRole = String(u.roleCode || u.role || '').toUpperCase();
        
        return topLevelRole === 'ZBH' || topLevelRole.includes('ZONAL BUSINESS HEAD') || roles.some((r: string) => {
            const roleStr = String(r || '').toUpperCase();
            return roleStr === 'ZBH' || roleStr === 'ZONE BUSINESS HEAD' || roleStr === 'ZONAL BUSINESS HEAD';
        });
    });
    const dropdownUsers = filteredZBHUsers.length > 0 ? filteredZBHUsers : (userAssignedData || []);

    // PRE-FILLING: When editing an existing zone, find its current ZBH from master data
    React.useEffect(() => {
        if (editingZoneId && isOpen) {
            // we already have the zonalBusinessHeadId passed as prop FROM MasterPage
        }
    }, [editingZoneId, isOpen]);

    return (
        <Dialog open={isOpen} onOpenChange={onOpenChange}>
            <DialogContent className="max-w-md">
                <DialogHeader>
                    <DialogTitle>{editingZoneId ? 'Edit' : 'Add'} Zone</DialogTitle>
                    <DialogDescription>Configure zonal details and geographical boundaries</DialogDescription>
                </DialogHeader>
                <div className="space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                        <div>
                            <Label>Zone Name</Label>
                            <Input 
                                placeholder="e.g., North Zone" 
                                className="mt-2 text-slate-900" 
                                value={zoneName} 
                                onChange={(e: any) => setZoneName(e.target.value)} 
                            />
                        </div>
                        <div>
                            <Label>Zone Code</Label>
                            <Input 
                                placeholder="e.g., NZ" 
                                className="mt-2 text-slate-900" 
                                value={zoneCode} 
                                onChange={(e: any) => setZoneCode(e.target.value)} 
                            />
                        </div>
                    </div>

                    <div>
                        <Label>Zonal Business Head</Label>
                        <Select value={zonalBusinessHeadId} onValueChange={setZonalBusinessHeadId}>
                            <SelectTrigger className="mt-2 w-full text-slate-900">
                                <SelectValue placeholder="Select Head" />
                            </SelectTrigger>
                            <SelectContent className="max-h-60">
                                <SelectItem value="none">None / Unassigned</SelectItem>
                                {dropdownUsers.map((user) => (
                                    <SelectItem key={user.id} value={user.id}>
                                        {user.name} ({user.email})
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                    </div>

                    <div>
                        <Label>Description</Label>
                        <Textarea 
                            placeholder="Describe the zone's coverage..." 
                            className="mt-2 text-slate-900" 
                            rows={3}
                            value={zoneDescription} 
                            onChange={(e: any) => setZoneDescription(e.target.value)} 
                        />
                    </div>
                    <div className="flex gap-3 pt-4">
                        <Button variant="outline" className="flex-1" onClick={() => onOpenChange(false)}>Cancel</Button>
                        <Button className="flex-1 bg-re-red hover:bg-re-red-hover" onClick={onSave}>Save Zone</Button>
                    </div>
                </div>
            </DialogContent>
        </Dialog>
    );
};
