import React, { useEffect, useMemo, useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from '@/components/ui/command';
import { Check, ChevronsUpDown } from 'lucide-react';
import { toast } from 'sonner';
import { masterService } from '@/services/master.service';
import { cn } from '@/components/ui/utils';

type DealerRow = {
  dealerId: string;
  dealerName: string;
  legalName: string;
  dealerCode: string;
  status: string;
  assignedAsm: null | {
    id: string;
    fullName: string;
    email: string;
    employeeId?: string;
  };
  assignedAt?: string | null;
};

type AsmUser = {
  id: string;
  fullName: string;
  email: string;
  employeeId?: string;
};

type AsmSearchSelectProps = {
  value: string;
  onChange: (value: string) => void;
  asmUsers: AsmUser[];
  className?: string;
};

const AsmSearchSelect: React.FC<AsmSearchSelectProps> = ({ value, onChange, asmUsers, className }) => {
  const [open, setOpen] = useState(false);
  const selectedAsm = asmUsers.find((u) => u.id === value);

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          role="combobox"
          aria-expanded={open}
          className={cn('w-full min-w-0 justify-between', className)}
        >
          <span className="truncate text-left">
            {value === '__none__'
              ? 'Unassign'
              : selectedAsm
              ? `${selectedAsm.fullName} (${selectedAsm.employeeId || selectedAsm.email})`
              : 'Select ASM'}
          </span>
          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-[360px] max-w-[90vw] p-0">
        <Command>
          <CommandInput placeholder="Search ASM by name/email/id..." />
          <CommandList className="max-h-64 overflow-y-auto custom-scrollbar-slim">
            <CommandEmpty>No ASM found.</CommandEmpty>
            <CommandGroup>
              <CommandItem
                value="Unassign __none__"
                onSelect={() => {
                  onChange('__none__');
                  setOpen(false);
                }}
              >
                <Check className={cn('mr-2 h-4 w-4', value === '__none__' ? 'opacity-100' : 'opacity-0')} />
                Unassign
              </CommandItem>
              {asmUsers.map((asm) => (
                <CommandItem
                  key={asm.id}
                  value={`${asm.fullName} ${asm.email} ${asm.employeeId || ''}`}
                  onSelect={() => {
                    onChange(asm.id);
                    setOpen(false);
                  }}
                >
                  <Check className={cn('mr-2 h-4 w-4', value === asm.id ? 'opacity-100' : 'opacity-0')} />
                  {asm.fullName} ({asm.employeeId || asm.email})
                </CommandItem>
              ))}
            </CommandGroup>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
};

export const DealerAsmAssignment: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [dealers, setDealers] = useState<DealerRow[]>([]);
  const [asmUsers, setAsmUsers] = useState<AsmUser[]>([]);
  const [draft, setDraft] = useState<Record<string, string>>({});

  const fetchData = async () => {
    try {
      setLoading(true);
      const res: any = await (masterService as any).getDealerAsmMappings();
      if (res?.success) {
        setDealers(res.data?.dealers || []);
        setAsmUsers(res.data?.asmUsers || []);
      }
    } catch (error: any) {
      toast.error(error?.response?.data?.message || 'Failed to load dealer ASM mappings');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  const sortedDealers = useMemo(
    () =>
      [...dealers].sort((a, b) => {
        const aActive = String(a.status || '').toLowerCase() === 'active';
        const bActive = String(b.status || '').toLowerCase() === 'active';
        if (aActive !== bActive) return aActive ? -1 : 1;
        return String(a.dealerName || '').localeCompare(String(b.dealerName || ''));
      }),
    [dealers]
  );

  const saveMapping = async (dealerId: string) => {
    const selectedAsm = draft[dealerId] || '';
    try {
      const res: any = await (masterService as any).saveDealerAsmMapping({
        dealerId,
        asmUserId: selectedAsm === '__none__' ? null : selectedAsm || null,
      });
      if (res?.success) {
        toast.success(res.message || 'Dealer ASM mapping updated');
        await fetchData();
      } else {
        toast.error(res?.message || 'Failed to save mapping');
      }
    } catch (error: any) {
      toast.error(error?.response?.data?.message || 'Failed to save mapping');
    }
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>Dealer-Level ASM Assignment</CardTitle>
        <CardDescription>
          Assign Sales ASM to onboarded dealers. DD-AM remains district-level in the section above.
        </CardDescription>
      </CardHeader>
      <CardContent>
        {loading ? (
          <p className="text-sm text-slate-500">Loading mappings...</p>
        ) : (
          <Table className="w-full">
            <TableHeader>
              <TableRow>
                <TableHead>Dealer</TableHead>
                <TableHead>Dealer Code</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Current ASM</TableHead>
                <TableHead>Assign ASM</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {sortedDealers.length === 0 && (
                <TableRow>
                  <TableCell colSpan={5} className="text-center text-slate-500 py-8">
                    No dealers available for ASM mapping yet.
                  </TableCell>
                </TableRow>
              )}
              {sortedDealers.map((dealer) => (
                <TableRow key={dealer.dealerId}>
                  <TableCell>
                    <div className="flex flex-col">
                      <span className="font-medium">{dealer.dealerName}</span>
                      <span className="text-xs text-slate-500">{dealer.legalName}</span>
                    </div>
                  </TableCell>
                  <TableCell>{dealer.dealerCode || 'N/A'}</TableCell>
                  <TableCell>
                    <Badge 
                      variant={String(dealer.status || '').toLowerCase() === 'active' ? 'default' : 'secondary'}
                      className={String(dealer.status || '').toLowerCase() === 'active' ? 'bg-emerald-100 text-emerald-700 hover:bg-emerald-200' : ''}
                    >
                      {dealer.status || 'Unknown'}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    {dealer.assignedAsm ? (
                      <div className="flex flex-col min-w-0">
                        <span>{dealer.assignedAsm.fullName}</span>
                        <span className="text-xs text-slate-500 truncate">{dealer.assignedAsm.employeeId || dealer.assignedAsm.email}</span>
                      </div>
                    ) : (
                      <span className="text-slate-400 text-sm">Unassigned</span>
                    )}
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2 w-full">
                      <AsmSearchSelect
                        asmUsers={asmUsers}
                        value={draft[dealer.dealerId] ?? dealer.assignedAsm?.id ?? '__none__'}
                        onChange={(val) => setDraft((prev) => ({ ...prev, [dealer.dealerId]: val }))}
                        className="flex-1 min-w-[180px]"
                      />
                      <Button size="sm" className="shrink-0 bg-re-red hover:bg-re-red-hover text-white" onClick={() => saveMapping(dealer.dealerId)}>
                        Assign
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        )}
      </CardContent>
    </Card>
  );
};

