import { Avatar } from '@/components/base/avatar/avatar';
import { Badge } from '@/components/base/badges/badges';
import { Button } from '@/components/base/buttons/button';
import { LeadStatusBadge } from '@/components/shared/status-badge';
import { SourceTag } from '@/components/shared/source-tag';
import { AgeIndicator } from '@/components/shared/age-indicator';
import { formatPhone, getInitials } from '@/lib/format';
import { cx } from '@/utils/cx';
import type { Lead } from '@/types/entities';

interface LeadCardProps {
    lead: Lead;
    onAssign: (lead: Lead) => void;
    onMessage: (lead: Lead) => void;
    onMarkSpam: (lead: Lead) => void;
    onMerge: (lead: Lead) => void;
    onLogCall?: (lead: Lead) => void;
    onUpdateStatus?: (lead: Lead) => void;
}

const sourceLabelMap: Record<string, string> = {
    FACEBOOK_AD: 'Facebook',
    INSTAGRAM: 'Instagram',
    GOOGLE_AD: 'Google',
    GOOGLE_MY_BUSINESS: 'GMB',
    WHATSAPP: 'WhatsApp',
    WEBSITE: 'Website',
    REFERRAL: 'Referral',
    WALK_IN: 'Walk-in',
    PHONE: 'Phone',
    OTHER: 'Other',
};

export const LeadCard = ({ lead, onAssign, onMessage, onMarkSpam, onMerge, onLogCall, onUpdateStatus }: LeadCardProps) => {
    const firstName = lead.contactName?.firstName ?? '';
    const lastName = lead.contactName?.lastName ?? '';
    const name = `${firstName} ${lastName}`.trim() || 'Unknown';
    const initials = firstName && lastName ? getInitials(firstName, lastName) : '??';
    const phone = lead.contactPhone?.[0] ? formatPhone(lead.contactPhone[0]) : '';
    const sourceLabel = lead.leadSource ? sourceLabelMap[lead.leadSource] ?? lead.leadSource : '';
    const isSpam = (lead.spamScore ?? 0) >= 60;
    const isDuplicate = lead.isDuplicate === true;
    const isAssigned = lead.assignedAgent !== null && lead.leadStatus !== 'NEW';

    return (
        <div
            className={cx(
                'flex items-center gap-4 rounded-2xl border border-secondary p-5 transition hover:shadow-md',
                isSpam ? 'bg-warning-primary' : 'bg-primary',
            )}
        >
            {/* Avatar */}
            <Avatar size="md" initials={initials} />

            {/* Middle content */}
            <div className="min-w-0 flex-1">
                <div className="flex flex-wrap items-center gap-2">
                    <span className="text-sm font-semibold text-primary">{name}</span>
                    {lead.leadStatus && <LeadStatusBadge status={lead.leadStatus} />}
                    {isSpam && (
                        <Badge size="sm" type="pill-color" color="error">
                            {lead.spamScore}% Spam Risk
                        </Badge>
                    )}
                    {isDuplicate && (
                        <Badge size="sm" type="pill-color" color="warning">
                            Duplicate
                        </Badge>
                    )}
                </div>
                <p className="mt-0.5 truncate text-xs text-tertiary">
                    {phone}
                    {lead.interestedService && ` · ${lead.interestedService}`}
                    {sourceLabel && ` · via ${sourceLabel}`}
                    {lead.utmCampaign && ` · ${lead.utmCampaign}`}
                </p>
            </div>

            {/* Age + Source */}
            <div className="flex items-center gap-3">
                {lead.createdAt && <AgeIndicator dateStr={lead.createdAt} />}
                {lead.leadSource && <SourceTag source={lead.leadSource} />}
            </div>

            {/* Action buttons */}
            <div className="flex items-center gap-2">
                {isSpam ? (
                    <>
                        <Button size="sm" color="secondary-destructive" onClick={() => onMarkSpam(lead)}>
                            Mark Spam
                        </Button>
                        <Button size="sm" color="secondary" onClick={() => onMessage(lead)}>
                            Review
                        </Button>
                    </>
                ) : isDuplicate ? (
                    <>
                        <Button size="sm" color="primary" onClick={() => onAssign(lead)}>
                            Assign
                        </Button>
                        <Button size="sm" color="secondary" onClick={() => onMerge(lead)}>
                            Merge
                        </Button>
                    </>
                ) : isAssigned ? (
                    <>
                        <Button size="sm" color="primary" onClick={() => onLogCall?.(lead)}>
                            Call
                        </Button>
                        <Button size="sm" color="secondary" onClick={() => onUpdateStatus?.(lead)}>
                            Disposition
                        </Button>
                    </>
                ) : (
                    <>
                        <Button size="sm" color="primary" onClick={() => onAssign(lead)}>
                            Assign
                        </Button>
                        <Button size="sm" color="secondary" onClick={() => onMessage(lead)}>
                            Message
                        </Button>
                    </>
                )}
            </div>
        </div>
    );
};
