import { Dialog, Modal, ModalOverlay } from '@/components/application/modals/modal';
import { Avatar } from '@/components/base/avatar/avatar';
import { Button } from '@/components/base/buttons/button';
import { formatPhone, getInitials } from '@/lib/format';
import type { Lead } from '@/types/entities';

type MarkSpamModalProps = {
    isOpen: boolean;
    onOpenChange: (open: boolean) => void;
    lead: Lead;
    onConfirm: () => void;
};

type SpamFactor = {
    icon: string;
    description: string;
    score: number;
};

const computeSpamFactors = (lead: Lead): SpamFactor[] => {
    const factors: SpamFactor[] = [];

    const firstName = lead.contactName?.firstName ?? '';
    const lastName = lead.contactName?.lastName ?? '';
    if (firstName.length < 3 && lastName.length < 3) {
        factors.push({ icon: '👤', description: 'Name is unusually short (under 3 characters each)', score: 30 });
    }

    if (!lead.contactEmail || lead.contactEmail.length === 0) {
        factors.push({ icon: '📧', description: 'No email address provided', score: 10 });
    }

    if (lead.createdAt) {
        const hour = new Date(lead.createdAt).getHours();
        if (hour >= 0 && hour < 5) {
            factors.push({ icon: '🌙', description: 'Submitted during late night hours (12–5 AM)', score: 20 });
        }
    }

    if (lead.contactAttempts !== null && lead.contactAttempts === 0 && lead.createdAt) {
        factors.push({ icon: '⚡', description: 'Submitted with no contact attempts — possible bot', score: 18 });
    }

    if (!lead.campaignId) {
        factors.push({ icon: '📊', description: 'No associated campaign or ad source', score: 10 });
    }

    return factors.filter((f) => f.score > 0);
};

export const MarkSpamModal = ({ isOpen, onOpenChange, lead, onConfirm }: MarkSpamModalProps) => {
    const factors = computeSpamFactors(lead);
    const computedScore = Math.min(100, factors.reduce((acc, f) => acc + f.score, 0));
    const displayScore = lead.spamScore ?? computedScore;

    const firstName = lead.contactName?.firstName ?? '';
    const lastName = lead.contactName?.lastName ?? '';
    const fullName = `${firstName} ${lastName}`.trim() || 'Unknown Lead';
    const initials = getInitials(firstName || 'U', lastName || 'L');
    const phone = lead.contactPhone?.[0] ? formatPhone(lead.contactPhone[0]) : '—';
    const email = lead.contactEmail?.[0]?.address ?? '—';
    const source = lead.leadSource ?? '—';

    const handleConfirm = () => {
        onConfirm();
        onOpenChange(false);
    };

    return (
        <ModalOverlay isOpen={isOpen} onOpenChange={onOpenChange} isDismissable>
            <Modal className="sm:max-w-lg">
                <Dialog>
                    {() => (
                        <div className="flex w-full flex-col 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">Mark as Spam</h2>
                                <p className="mt-1 text-sm text-tertiary">
                                    Review spam indicators before marking this lead.
                                </p>
                            </div>

                            {/* Body */}
                            <div className="flex flex-col gap-4 px-6 py-4 overflow-y-auto max-h-[65vh]">
                                {/* Lead summary */}
                                <div className="flex items-center gap-3 rounded-xl bg-error-primary p-4">
                                    <Avatar initials={initials} size="md" />
                                    <div className="flex flex-1 flex-col min-w-0">
                                        <span className="text-sm font-semibold text-primary truncate">{fullName}</span>
                                        <span className="text-xs text-tertiary truncate">{phone}</span>
                                        <span className="text-xs text-tertiary truncate">{email}</span>
                                        <span className="text-xs text-quaternary">Source: {source}</span>
                                    </div>
                                    <div className="flex shrink-0 flex-col items-center">
                                        <span className="text-display-xs font-bold text-error-primary">{displayScore}</span>
                                        <span className="text-xs text-error-primary/70">spam score</span>
                                    </div>
                                </div>

                                {/* Spam factors */}
                                {factors.length > 0 && (
                                    <div className="flex flex-col gap-2">
                                        <p className="text-sm font-medium text-secondary">Spam indicators</p>
                                        {factors.map((factor, idx) => (
                                            <div
                                                key={idx}
                                                className="flex items-center gap-2 rounded-lg bg-secondary p-3"
                                            >
                                                <span className="text-base">{factor.icon}</span>
                                                <span className="flex-1 text-xs text-secondary">{factor.description}</span>
                                                <span className="shrink-0 text-xs font-bold text-error-primary">+{factor.score}</span>
                                            </div>
                                        ))}
                                    </div>
                                )}

                                {/* Info block */}
                                <div className="rounded-xl border border-error_subtle bg-error-primary/50 p-3.5">
                                    <p className="text-xs font-bold text-primary">This can be undone</p>
                                    <p className="mt-0.5 text-xs text-secondary">
                                        You can unmark this lead as spam later from the lead details panel or by filtering the Spam queue.
                                    </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-destructive" onClick={handleConfirm}>
                                    Mark as Spam
                                </Button>
                            </div>
                        </div>
                    )}
                </Dialog>
            </Modal>
        </ModalOverlay>
    );
};
