import React, { useMemo } from 'react';
import { useSelector } from 'react-redux';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { UserCog, Plus, Edit2, Trash2, Users } from 'lucide-react';
import { RootState } from '@/store';

interface ASMManagementProps {
  selectedZone: string;
  onAddASM: () => void;
  onEditASM: (asm: any) => void;
  onDeleteASM: (id: string, name: string) => void;
}

export const ASMManagement: React.FC<ASMManagementProps> = ({ 
  selectedZone, onAddASM, onEditASM, onDeleteASM 
}) => {
  const { asms, zonalManagerMappings } = useSelector((state: RootState) => state.master);

  const filteredASMs = asms.filter((a: any) => selectedZone === 'all' || a.zoneId === selectedZone);

  const districtsAssignedToOthers = useMemo(() => {
    const map: Record<string, string[]> = {};
    [...asms, ...zonalManagerMappings].forEach(m => {
      const dists = (m as any).areasManaged || (m as any).districts || [];
      dists.forEach((d: string) => {
        if (!map[d]) map[d] = [];
        if (!map[d].includes(m.name)) map[d].push(m.name);
      });
    });
    return map;
  }, [asms, zonalManagerMappings]);

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle>District Development Area Managers (DD-AM)</CardTitle>
            <CardDescription>Manage DD-AM users across districts (multi-district)</CardDescription>
          </div>
          <Button onClick={onAddASM} className="bg-re-red hover:bg-re-red-hover">
            <Plus className="w-4 h-4 mr-2" />
            Add DD-AM
          </Button>
        </div>
      </CardHeader>
      <CardContent>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>DD-AM Code</TableHead>
              <TableHead>Name</TableHead>
              <TableHead>Zone</TableHead>
              <TableHead>Region</TableHead>
              <TableHead>Districts Managed</TableHead>
              <TableHead>Contact</TableHead>
              <TableHead>Status</TableHead>
              <TableHead className="text-right">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredASMs.map((asm: any) => (
              <TableRow key={asm.id}>
                <TableCell>
                  <div className="flex items-center gap-2">
                    <UserCog className="w-4 h-4 text-green-600" />
                    <span className="font-medium">{asm.asmCode || 'N/A'}</span>
                  </div>
                </TableCell>
                <TableCell>{asm.name}</TableCell>
                <TableCell>
                  <Badge variant="outline">{asm.zoneName}</Badge>
                </TableCell>
                <TableCell className="text-sm text-slate-600">{asm.regionName}</TableCell>
                <TableCell>
                  <div className="flex flex-wrap gap-1">
                    {asm.areasManaged.map((area: any, idx: number) => {
                      const areaId = typeof area === 'string' ? area : area.id;
                      const areaName = typeof area === 'string' ? area : area.name;
                      const otherManagers = (districtsAssignedToOthers[areaId] || []).filter((name: string) => name !== asm.name);
                      const isShared = otherManagers.length > 0;
                      return (
                        <Badge 
                          key={idx} 
                          variant={isShared ? "outline" : "secondary"} 
                          className={`text-xs ${isShared ? "border-red-300 bg-red-50 text-re-red-hover font-medium" : ""}`}
                          title={isShared ? `Also managed by: ${otherManagers.join(', ')}` : undefined}
                        >
                          {areaName}
                          {isShared && <Users className="w-2.5 h-2.5 ml-1 inline" />}
                        </Badge>
                      );
                    })}
                  </div>
                </TableCell>
                <TableCell>
                  <div className="text-sm">
                    <p className="text-slate-900">{asm.email}</p>
                    <p className="text-slate-500">{asm.phone}</p>
                  </div>
                </TableCell>
                <TableCell>
                  <Badge variant={asm.status === 'Active' ? 'default' : 'secondary'} className={asm.status === 'Active' ? 'bg-emerald-100 text-emerald-700' : ''}>
                    {asm.status}
                  </Badge>
                </TableCell>
                <TableCell className="text-right">
                  <div className="flex gap-2 justify-end">
                    <Button variant="ghost" size="sm" onClick={() => onEditASM(asm)}>
                      <Edit2 className="w-4 h-4" />
                    </Button>
                    <Button variant="ghost" size="sm" onClick={() => onDeleteASM(asm.id, asm.name)} className="text-re-red hover:text-re-red-hover hover:bg-red-50">
                      <Trash2 className="w-4 h-4" />
                    </Button>
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </CardContent>
    </Card>
  );
};
