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

type WhatsAppSendModalProps = {
    isOpen: boolean;
    onOpenChange: (open: boolean) => void;
    selectedLeads: Lead[];
    templates: WhatsAppTemplate[];
    onSend: (templateId: string) => void;
};

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

const getLeadPhone = (lead: Lead) => {
    if (lead.contactPhone && lead.contactPhone.length > 0) {
        return formatPhone(lead.contactPhone[0]);
    }
    return '';
};

const populateVariables = (body: string, lead: Lead) => {
    const name = getLeadName(lead);
    return body
        .replace(/\{\{name\}\}/gi, name)
        .replace(/\{\{first_name\}\}/gi, lead.contactName?.firstName ?? name)
        .replace(/\{\{service\}\}/gi, lead.interestedService ?? 'our services');
};

const highlightVariables = (text: string) => {
    const parts = text.split(/(\{\{[^}]+\}\})/g);
    return parts.map((part, i) => {
        if (/^\{\{[^}]+\}\}$/.test(part)) {
            return (
                <span key={i} className="rounded bg-success-secondary px-1 font-semibold text-success-primary">
                    {part}
                </span>
            );
        }
        return <span key={i}>{part}</span>;
    });
};

export const WhatsAppSendModal = ({ isOpen, onOpenChange, selectedLeads, templates, onSend }: WhatsAppSendModalProps) => {
    const approvedTemplates = templates.filter((t) => t.approvalStatus === 'APPROVED');
    const [selectedTemplateId, setSelectedTemplateId] = useState<string>(approvedTemplates[0]?.id ?? '');

    const selectedTemplate = templates.find((t) => t.id === selectedTemplateId);
    const previewLead = selectedLeads[0];

    const selectItems = approvedTemplates.map((t) => ({
        id: t.id,
        label: t.name ?? 'Untitled Template',
        supportingText: t.linkedCampaignName ?? undefined,
    }));

    const handleSend = () => {
        if (selectedTemplateId) {
            onSend(selectedTemplateId);
            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">Send WhatsApp Message</h2>
                                <p className="mt-1 text-sm text-tertiary">
                                    Send a template message to {selectedLeads.length} selected{' '}
                                    {selectedLeads.length === 1 ? 'lead' : 'leads'} via WhatsApp.
                                </p>
                            </div>

                            {/* Body */}
                            <div className="flex flex-col gap-4 px-6 py-4 overflow-y-auto max-h-[65vh]">
                                {/* Recipient chips */}
                                <div className="flex flex-wrap gap-2">
                                    {selectedLeads.map((lead) => (
                                        <span
                                            key={lead.id}
                                            className="flex items-center gap-1 rounded-full border border-brand bg-brand-primary px-3 py-1 text-xs text-brand-secondary"
                                        >
                                            <span className="font-medium">{getLeadName(lead)}</span>
                                            {getLeadPhone(lead) && (
                                                <span className="text-brand-tertiary">· {getLeadPhone(lead)}</span>
                                            )}
                                        </span>
                                    ))}
                                </div>

                                {/* Template select */}
                                <Select
                                    label="Template"
                                    placeholder="Select a template"
                                    size="sm"
                                    items={selectItems}
                                    selectedKey={selectedTemplateId}
                                    onSelectionChange={(key) => setSelectedTemplateId(String(key))}
                                >
                                    {(item) => (
                                        <Select.Item id={item.id} supportingText={item.supportingText}>
                                            {item.label}
                                        </Select.Item>
                                    )}
                                </Select>

                                {/* Preview */}
                                {selectedTemplate && (
                                    <div className="flex flex-col gap-2">
                                        <p className="text-sm font-medium text-secondary">Preview</p>
                                        <div className="rounded-xl p-3" style={{ backgroundColor: '#e5ddd5' }}>
                                            <div className="max-w-[85%] rounded-xl rounded-tl-none bg-white px-3 py-2 shadow-sm">
                                                <p className="text-sm text-primary leading-relaxed">
                                                    {previewLead
                                                        ? highlightVariables(populateVariables(selectedTemplate.body ?? '', previewLead))
                                                        : highlightVariables(selectedTemplate.body ?? '')}
                                                </p>
                                                <p className="mt-1 text-right text-xs text-quaternary">12:00 PM ✓✓</p>
                                            </div>
                                        </div>
                                        <p className="text-xs text-quaternary">
                                            Variables auto-populated from lead data. Template is pre-approved by WhatsApp.
                                        </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={!selectedTemplateId}
                                    onClick={handleSend}
                                    className={cx('bg-success-solid hover:bg-success-solid/90 text-white')}
                                >
                                    Send to {selectedLeads.length} {selectedLeads.length === 1 ? 'Lead' : 'Leads'}
                                </Button>
                            </div>
                        </div>
                    )}
                </Dialog>
            </Modal>
        </ModalOverlay>
    );
};
