import { useState } from 'react';
import { Button } from '@/components/base/buttons/button';
import { Dialog, Modal, ModalOverlay } from '@/components/application/modals/modal';
import { getInitials } from '@/lib/format';
import type { Agent, Lead } from '@/types/entities';
import { cx } from '@/utils/cx';

type AssignModalProps = {
    isOpen: boolean;
    onOpenChange: (open: boolean) => void;
    selectedLeads: Lead[];
    agents: Agent[];
    onAssign: (agentId: string) => void;
};

const agentColors = ['bg-brand-secondary', 'bg-success-solid', 'bg-warning-solid', 'bg-error-solid'];

export const AssignModal = ({ isOpen, onOpenChange, selectedLeads, agents, onAssign }: AssignModalProps) => {
    const [selectedAgentId, setSelectedAgentId] = useState<string | null>(null);
    const [removedLeadIds, setRemovedLeadIds] = useState<Set<string>>(new Set());

    const visibleLeads = selectedLeads.filter((l) => !removedLeadIds.has(l.id));
    const selectedAgent = agents.find((a) => a.id === selectedAgentId);

    const handleRemoveLead = (leadId: string) => {
        setRemovedLeadIds((prev) => new Set([...prev, leadId]));
    };

    const handleAssign = () => {
        if (selectedAgentId) {
            onAssign(selectedAgentId);
            onOpenChange(false);
        }
    };

    const getLeadName = (lead: Lead) => {
        if (lead.contactName) {
            return `${lead.contactName.firstName} ${lead.contactName.lastName}`.trim();
        }
        return 'Unknown';
    };

    return (
        <ModalOverlay isOpen={isOpen} onOpenChange={onOpenChange} isDismissable>
            <Modal className="sm:max-w-lg">
                <Dialog>
                    {() => (
                        <div className="flex w-full flex-col gap-0 rounded-xl bg-primary shadow-xl ring-1 ring-secondary overflow-hidden">
                            {/* Header */}
                            <div className="px-6 pt-6 pb-4 border-b border-secondary">
                                <h2 className="text-lg font-semibold text-primary">Assign to Call Center</h2>
                                <p className="mt-1 text-sm text-tertiary">
                                    Assign {visibleLeads.length} selected {visibleLeads.length === 1 ? 'lead' : 'leads'} to a call center agent for outbound calling.
                                </p>
                            </div>

                            {/* Body */}
                            <div className="flex flex-col gap-4 px-6 py-4 overflow-y-auto max-h-[60vh]">
                                {/* Recipient chips */}
                                {visibleLeads.length > 0 && (
                                    <div className="flex flex-wrap gap-2">
                                        {visibleLeads.map((lead) => (
                                            <span
                                                key={lead.id}
                                                className="flex items-center gap-1.5 rounded-full border border-brand bg-brand-primary px-3 py-1 text-xs text-brand-secondary"
                                            >
                                                {getLeadName(lead)}
                                                <button
                                                    type="button"
                                                    onClick={() => handleRemoveLead(lead.id)}
                                                    className="ml-0.5 flex items-center justify-center rounded-full text-brand-secondary hover:text-brand-secondary_hover transition duration-100 ease-linear"
                                                    aria-label={`Remove ${getLeadName(lead)}`}
                                                >
                                                    ×
                                                </button>
                                            </span>
                                        ))}
                                    </div>
                                )}

                                {/* Agent selection */}
                                <div className="flex flex-col gap-2">
                                    <p className="text-sm font-medium text-secondary">Select agent</p>
                                    {agents.map((agent, idx) => {
                                        const isSelected = selectedAgentId === agent.id;
                                        const colorClass = agentColors[idx % agentColors.length];
                                        return (
                                            <button
                                                key={agent.id}
                                                type="button"
                                                onClick={() => setSelectedAgentId(agent.id)}
                                                className={cx(
                                                    'flex w-full cursor-pointer items-center gap-3 rounded-xl border-2 p-3 text-left transition duration-100 ease-linear',
                                                    isSelected
                                                        ? 'border-brand bg-brand-primary'
                                                        : 'border-secondary hover:border-brand/50',
                                                )}
                                            >
                                                <div
                                                    className={cx(
                                                        'flex size-9 shrink-0 items-center justify-center rounded-full text-sm font-semibold text-white',
                                                        colorClass,
                                                    )}
                                                >
                                                    {agent.initials ?? getInitials(agent.name?.split(' ')[0] ?? '', agent.name?.split(' ')[1] ?? '')}
                                                </div>
                                                <div className="flex flex-1 flex-col min-w-0">
                                                    <span className="text-sm font-semibold text-primary truncate">{agent.name}</span>
                                                    <span className="text-xs text-tertiary truncate">
                                                        {agent.isOnShift ? '🟢 On shift' : '⚫ Off shift'} · Avg {agent.avgResponseHours}h response
                                                    </span>
                                                </div>
                                                <div className="flex flex-col items-end shrink-0">
                                                    <span className="text-lg font-bold text-primary">{agent.activeLeadCount ?? 0}</span>
                                                    <span className="text-xs text-quaternary">Active leads</span>
                                                </div>
                                            </button>
                                        );
                                    })}
                                </div>

                                {/* Warning block */}
                                <div className="rounded-xl border border-warning bg-warning-primary p-3.5">
                                    <p className="text-xs font-bold text-warning-primary">⚠ This action cannot be undone</p>
                                    <p className="mt-0.5 text-xs text-warning-primary/80">
                                        Once assigned, the lead status will change to Contacted and the agent will be notified immediately.
                                    </p>
                                </div>
                            </div>

                            {/* Footer */}
                            <div className="flex items-center justify-end gap-3 border-t border-secondary px-6 py-4">
                                <Button size="md" color="secondary" onClick={() => onOpenChange(false)}>
                                    Cancel
                                </Button>
                                <Button
                                    size="md"
                                    color="primary"
                                    isDisabled={!selectedAgentId || visibleLeads.length === 0}
                                    onClick={handleAssign}
                                >
                                    Assign {visibleLeads.length} {visibleLeads.length === 1 ? 'Lead' : 'Leads'}
                                    {selectedAgent ? ` to ${selectedAgent.name}` : ''}
                                </Button>
                            </div>
                        </div>
                    )}
                </Dialog>
            </Modal>
        </ModalOverlay>
    );
};
