import InputError from '@/components/input-error';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
    AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { useTranslation } from '@/hooks/use-translation';
import { WhatsAppApprovalStatus, WhatsAppTemplate } from '@/types';
import { Link, router, useForm } from '@inertiajs/react';
import { BarChart3, Eye, RefreshCw, Send, Trash } from 'lucide-react';
import React from 'react';
import { toast } from 'sonner';
import SelectWithSearch from './search-select';

type Contact = { id: number; name: string; phone: string; opted_in: boolean };
type Recipient = { type: 'client' | 'owner'; id: number; name: string; phone: string };

type WhatsAppTemplateForm = {
    friendly_name: string;
    body: string;
};

const statusConfig: Record<WhatsAppApprovalStatus, string> = {
    draft: 'bg-gray-200 text-gray-700',
    received: 'bg-blue-100 text-blue-800',
    pending: 'bg-amber-100 text-amber-800',
    approved: 'bg-green-100 text-green-800',
    rejected: 'bg-red-100 text-red-800',
};

const formatDate = (value: string | null) =>
    value ? new Date(value).toLocaleString('fr-FR', { dateStyle: 'short', timeStyle: 'short' }) : '—';

interface WhatsAppPanelProps {
    templates: WhatsAppTemplate[];
    clients: Contact[];
    owners: Contact[];
}

export default function WhatsAppPanel({ templates, clients, owners }: WhatsAppPanelProps) {
    const { t } = useTranslation();

    // ── Create-template form ──────────────────────────────────────────────
    // {{1}} (the client's name) is the only variable: the user types it directly in the message.
    const { data, setData, post, errors, processing, reset, setError, clearErrors } = useForm<WhatsAppTemplateForm>({
        friendly_name: '',
        body: '',
    });

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        clearErrors();

        // Front-end guard mirroring the server rules — fail instantly, no round-trip.
        const body = data.body.trim();
        let bodyError: string | null = null;
        if (/\{\{|\}\}/.test(body)) {
            bodyError = t('newsletters', 'body_no_braces');
        } else if (!/@(nom|name)\b/i.test(body)) {
            bodyError = t('newsletters', 'body_name_required');
        } else {
            const canonical = body.replace(/@(nom|name)\b/gi, '{{1}}');
            if (/^\{\{\s*\d+\s*\}\}/.test(canonical) || /\{\{\s*\d+\s*\}\}$/.test(canonical)) {
                bodyError = t('newsletters', 'body_variable_edge_error');
            }
        }

        if (bodyError) {
            setError('body', bodyError);
            return;
        }

        post(route('newsletters.whatsapp.templates.store'), {
            preserveScroll: true,
            preserveState: true, // stay on the WhatsApp tab; the list refreshes with the new template
            onSuccess: () => reset(),
            onError: () => toast.error(t('newsletters', 'submission_error')),
        });
    };

    // ── Per-template actions ──────────────────────────────────────────────
    const submitTemplate = (id: number) => {
        router.post(
            route('newsletters.whatsapp.templates.submit', id),
            {},
            { preserveScroll: true, preserveState: true, onError: () => toast.error(t('newsletters', 'submission_error')) },
        );
    };

    const refreshTemplate = (id: number) => {
        router.post(
            route('newsletters.whatsapp.templates.refresh', id),
            {},
            { preserveScroll: true, preserveState: true, onError: () => toast.error(t('newsletters', 'submission_error')) },
        );
    };

    const deleteTemplate = (id: number) => {
        router.delete(route('newsletters.whatsapp.templates.delete', id), {
            preserveScroll: true,
            preserveState: true,
            onError: () => toast.error(t('newsletters', 'submission_error')),
        });
    };

    // ── Send dialog state ─────────────────────────────────────────────────
    const [sendTemplate, setSendTemplate] = React.useState<WhatsAppTemplate | null>(null);

    // ── Message-preview dialog state ──────────────────────────────────────
    const [previewTemplate, setPreviewTemplate] = React.useState<WhatsAppTemplate | null>(null);

    // On entering the WhatsApp screen, refresh any template still awaiting Meta's decision
    // (received/pending) so the user sees up-to-date statuses without clicking Refresh.
    React.useEffect(() => {
        const hasPending = templates.some(
            (tpl) => tpl.approval_status === 'received' || tpl.approval_status === 'pending',
        );
        if (hasPending) {
            router.post(
                route('newsletters.whatsapp.templates.refresh_pending'),
                {},
                { preserveScroll: true, only: ['whatsappTemplates'] },
            );
        }
        // Run once on mount (i.e. when the WhatsApp tab is opened).
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    // Live preview: show the message with @nom replaced by a sample name, so the result is obvious.
    const bodyPreview = data.body.replace(/@(nom|name)\b/gi, t('newsletters', 'preview_sample_name'));

    return (
        <div className="space-y-8">
            <div>
                <h1 className="text-2xl font-semibold">{t('newsletters', 'whatsapp_templates')}</h1>
                <p className="mt-1 text-sm text-muted-foreground">{t('newsletters', 'whatsapp_intro')}</p>
            </div>

            {/* Create form */}
            <form onSubmit={handleSubmit} className="space-y-4 rounded-lg border bg-card p-4 shadow-sm">
                <h2 className="text-lg font-semibold">{t('newsletters', 'create_template')}</h2>

                <div>
                    <Label htmlFor="friendly_name">{t('newsletters', 'template_name')}</Label>
                    <Input
                        id="friendly_name"
                        type="text"
                        value={data.friendly_name}
                        onChange={(e) => setData('friendly_name', e.target.value)}
                        placeholder={t('newsletters', 'template_name_placeholder')}
                        className="mt-1"
                    />
                    <InputError message={errors.friendly_name} className="mt-2" />
                </div>

                <div>
                    <Label htmlFor="body">{t('newsletters', 'body')}</Label>
                    <Textarea
                        id="body"
                        value={data.body}
                        onChange={(e) => setData('body', e.target.value)}
                        placeholder={t('newsletters', 'body_placeholder')}
                        className="mt-1"
                        rows={4}
                    />
                    <p className="mt-1 text-xs text-muted-foreground">{t('newsletters', 'body_variable_hint')}</p>
                    <InputError message={errors.body} className="mt-2" />

                    {data.body.trim() !== '' && (
                        <div className="mt-3 rounded-md border bg-background p-3">
                            <p className="text-xs font-medium text-muted-foreground">{t('newsletters', 'preview')}</p>
                            <p className="mt-1 whitespace-pre-wrap text-sm">{bodyPreview}</p>
                        </div>
                    )}
                </div>

                <div className="flex justify-end">
                    <Button type="submit" disabled={processing} className="bg-secondary">
                        {processing ? t('newsletters', 'creating') : t('newsletters', 'create_template')}
                    </Button>
                </div>
            </form>

            {/* Template list */}
            <div>
                <h2 className="text-lg font-semibold">{t('newsletters', 'templates')}</h2>
                {templates.length === 0 ? (
                    <p className="mt-4 rounded-md border bg-card p-8 text-center text-muted-foreground">
                        {t('newsletters', 'no_templates')}
                    </p>
                ) : (
                    <div className="mt-4 space-y-3">
                        {templates.map((template) => (
                            <div
                                key={template.id}
                                className="flex flex-col gap-3 rounded-md border bg-card p-4 shadow-sm md:flex-row md:items-center md:justify-between"
                            >
                                <div className="min-w-0 space-y-1">
                                    <div className="flex flex-wrap items-center gap-2">
                                        <span className="font-medium">{template.friendly_name}</span>
                                        <Badge className={statusConfig[template.approval_status]}>
                                            {t('newsletters', template.approval_status)}
                                        </Badge>
                                    </div>
                                    <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
                                        <span>{t('newsletters', template.template_type)}</span>
                                        {template.approval_synced_at && (
                                            <>
                                                <span>·</span>
                                                <span>
                                                    {t('newsletters', 'synced_at')}: {formatDate(template.approval_synced_at)}
                                                </span>
                                            </>
                                        )}
                                    </div>
                                    {template.approval_status === 'rejected' && template.rejection_reason && (
                                        <p className="max-w-xl text-xs text-red-600">
                                            {t('newsletters', 'rejection_reason')}: {template.rejection_reason}
                                        </p>
                                    )}
                                </div>

                                <div className="flex shrink-0 flex-wrap items-center gap-2">
                                    <Button variant="outline" size="sm" onClick={() => setPreviewTemplate(template)}>
                                        <Eye className="mr-1.5 h-4 w-4" />
                                        {t('newsletters', 'view_message')}
                                    </Button>
                                    {template.approval_status === 'draft' && (
                                        <Button variant="outline" size="sm" onClick={() => submitTemplate(template.id)}>
                                            <Send className="mr-1.5 h-4 w-4" />
                                            {t('newsletters', 'submit_for_approval')}
                                        </Button>
                                    )}
                                    {(template.approval_status === 'received' || template.approval_status === 'pending') && (
                                        <Button variant="outline" size="sm" onClick={() => refreshTemplate(template.id)}>
                                            <RefreshCw className="mr-1.5 h-4 w-4" />
                                            {t('newsletters', 'refresh_status')}
                                        </Button>
                                    )}

                                    {template.approval_status === 'approved' && (
                                        <>
                                            <Button size="sm" onClick={() => setSendTemplate(template)}>
                                                <Send className="mr-1.5 h-4 w-4" />
                                                {t('newsletters', 'send_template')}
                                            </Button>
                                            <Button variant="outline" size="sm" asChild>
                                                <Link href={route('newsletters.whatsapp.templates.stats', template.id)}>
                                                    <BarChart3 className="mr-1.5 h-4 w-4" />
                                                    {t('newsletters', 'view_stats')}
                                                </Link>
                                            </Button>
                                        </>
                                    )}

                                    <AlertDialog>
                                        <AlertDialogTrigger asChild>
                                            <Button variant="ghost" size="sm" className="text-red-500 hover:text-red-600">
                                                <Trash className="h-4 w-4" />
                                            </Button>
                                        </AlertDialogTrigger>
                                        <AlertDialogContent>
                                            <AlertDialogHeader>
                                                <AlertDialogTitle>
                                                    {t('newsletters', 'confirm_delete_template')}
                                                </AlertDialogTitle>
                                                <AlertDialogDescription>
                                                    {t('newsletters', 'confirm_delete_template_message')}
                                                </AlertDialogDescription>
                                            </AlertDialogHeader>
                                            <AlertDialogFooter>
                                                <AlertDialogCancel>{t('newsletters', 'cancel')}</AlertDialogCancel>
                                                <AlertDialogAction onClick={() => deleteTemplate(template.id)}>
                                                    {t('newsletters', 'delete')}
                                                </AlertDialogAction>
                                            </AlertDialogFooter>
                                        </AlertDialogContent>
                                    </AlertDialog>
                                </div>
                            </div>
                        ))}
                    </div>
                )}
            </div>

            <SendDialog
                template={sendTemplate}
                clients={clients}
                owners={owners}
                onClose={() => setSendTemplate(null)}
            />

            <Dialog open={previewTemplate !== null} onOpenChange={(open) => !open && setPreviewTemplate(null)}>
                <DialogContent className="sm:max-w-lg">
                    <DialogHeader>
                        <DialogTitle>{previewTemplate?.friendly_name ?? t('newsletters', 'preview')}</DialogTitle>
                        <DialogDescription>{t('newsletters', 'preview')}</DialogDescription>
                    </DialogHeader>
                    {/* WhatsApp-style bubble — @nom shown with a sample name, like the create form. */}
                    <div className="rounded-lg bg-[#e7ffdb] p-4 text-sm whitespace-pre-wrap text-gray-900 shadow-sm">
                        {(previewTemplate?.body ?? '').replace(/@(nom|name)\b/gi, t('newsletters', 'preview_sample_name'))}
                    </div>
                </DialogContent>
            </Dialog>
        </div>
    );
}

interface SendDialogProps {
    template: WhatsAppTemplate | null;
    clients: Contact[];
    owners: Contact[];
    onClose: () => void;
}

function SendDialog({ template, clients, owners, onClose }: SendDialogProps) {
    const { t } = useTranslation();

    const [selectedOwners, setSelectedOwners] = React.useState<string[]>([]);
    const [selectedClients, setSelectedClients] = React.useState<string[]>([]);
    const [sending, setSending] = React.useState(false);

    const ownerLabel = React.useCallback((c: Contact) => `${c.name} (${c.phone})`, []);
    const clientLabel = React.useCallback((c: Contact) => `${c.name} (${c.phone})`, []);

    // Audience is decided by the template, not the user:
    //  - opt-in template  → people who have NOT accepted yet (pending + refused = not opted-in)
    //  - any other template → only people who replied YES (opted-in)
    const isOptin = template?.is_optin === true;
    const matchesAudience = React.useCallback((c: Contact) => (isOptin ? !c.opted_in : c.opted_in), [isOptin]);
    const visibleOwners = React.useMemo(() => owners.filter(matchesAudience), [owners, matchesAudience]);
    const visibleClients = React.useMemo(() => clients.filter(matchesAudience), [clients, matchesAudience]);

    // Map each option label back to its recipient object so the selection survives the round-trip.
    const ownerByLabel = React.useMemo(() => {
        const map = new Map<string, Recipient>();
        visibleOwners.forEach((o) => map.set(ownerLabel(o), { type: 'owner', id: o.id, name: o.name, phone: o.phone }));
        return map;
    }, [visibleOwners, ownerLabel]);

    const clientByLabel = React.useMemo(() => {
        const map = new Map<string, Recipient>();
        visibleClients.forEach((c) => map.set(clientLabel(c), { type: 'client', id: c.id, name: c.name, phone: c.phone }));
        return map;
    }, [visibleClients, clientLabel]);

    const ownerOptions = React.useMemo(() => visibleOwners.map(ownerLabel), [visibleOwners, ownerLabel]);
    const clientOptions = React.useMemo(() => visibleClients.map(clientLabel), [visibleClients, clientLabel]);

    const [checkAllOwners, setCheckAllOwners] = React.useState(false);
    const [checkAllClients, setCheckAllClients] = React.useState(false);

    React.useEffect(() => {
        // Reset every time the dialog opens/closes or the template changes (the audience differs
        // per template, so a stale selection must not carry over).
        setSelectedOwners([]);
        setSelectedClients([]);
        setCheckAllOwners(false);
        setCheckAllClients(false);
        if (!template) {
            setSending(false);
        }
    }, [template]);

    const toggleAllOwners = () => {
        const next = !checkAllOwners;
        setCheckAllOwners(next);
        setSelectedOwners(next ? ownerOptions : []);
    };

    const toggleAllClients = () => {
        const next = !checkAllClients;
        setCheckAllClients(next);
        setSelectedClients(next ? clientOptions : []);
    };

    const recipients: Recipient[] = React.useMemo(() => {
        const out: Recipient[] = [];
        selectedOwners.forEach((label) => {
            const r = ownerByLabel.get(label);
            if (r) out.push(r);
        });
        selectedClients.forEach((label) => {
            const r = clientByLabel.get(label);
            if (r) out.push(r);
        });
        return out;
    }, [selectedOwners, selectedClients, ownerByLabel, clientByLabel]);

    const hasContacts = clients.length > 0 || owners.length > 0;

    const handleSend = () => {
        if (!template || recipients.length === 0) return;
        setSending(true);
        router.post(
            route('newsletters.whatsapp.campaigns.send'),
            { template_id: template.id, recipients },
            {
                preserveScroll: true,
                preserveState: true,
                onSuccess: () => onClose(),
                onError: () => toast.error(t('newsletters', 'submission_error')),
                onFinish: () => setSending(false),
            },
        );
    };

    return (
        <Dialog open={template !== null} onOpenChange={(open) => !open && onClose()}>
            <DialogContent className="sm:max-w-2xl">
                <DialogHeader>
                    <DialogTitle>{template?.friendly_name ?? t('newsletters', 'send_template')}</DialogTitle>
                    <DialogDescription>{t('newsletters', 'recipients')}</DialogDescription>
                </DialogHeader>

                {hasContacts && (
                    <div className="flex items-center gap-2 rounded-md border bg-muted/40 px-3 py-2 text-sm">
                        <span className="font-medium">
                            {isOptin ? t('newsletters', 'audience_not_opted_in') : t('newsletters', 'audience_opted_in')}
                        </span>
                        <Badge className={`ml-auto ${isOptin ? 'bg-amber-100 text-amber-800' : 'bg-green-100 text-green-800'}`}>
                            {visibleOwners.length + visibleClients.length} {t('newsletters', 'contacts')}
                        </Badge>
                    </div>
                )}

                {!hasContacts ? (
                    <p className="rounded-md border bg-card p-6 text-center text-sm text-muted-foreground">
                        {t('newsletters', 'select_recipients_first')}
                    </p>
                ) : (
                    <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                        <div className="rounded-lg border p-2">
                            <div className="mb-2 flex items-center justify-between">
                                <Label className="text-sm font-semibold">{t('newsletters', 'owners')}</Label>
                                <div className="flex items-center space-x-2">
                                    <Checkbox
                                        id="send-select-all-owners"
                                        checked={checkAllOwners}
                                        onCheckedChange={toggleAllOwners}
                                        className="cursor-pointer"
                                    />
                                    <Label
                                        htmlFor="send-select-all-owners"
                                        className="cursor-pointer text-sm font-semibold"
                                    >
                                        {t('newsletters', 'select_all')}
                                    </Label>
                                </div>
                            </div>
                            <SelectWithSearch
                                users={ownerOptions}
                                value={selectedOwners}
                                onChange={setSelectedOwners}
                                placeholder={t('newsletters', 'search_owners')}
                            />
                        </div>

                        <div className="rounded-lg border p-2">
                            <div className="mb-2 flex items-center justify-between">
                                <Label className="text-sm font-semibold">{t('newsletters', 'clients')}</Label>
                                <div className="flex items-center space-x-2">
                                    <Checkbox
                                        id="send-select-all-clients"
                                        checked={checkAllClients}
                                        onCheckedChange={toggleAllClients}
                                        className="cursor-pointer"
                                    />
                                    <Label
                                        htmlFor="send-select-all-clients"
                                        className="cursor-pointer text-sm font-semibold"
                                    >
                                        {t('newsletters', 'select_all')}
                                    </Label>
                                </div>
                            </div>
                            <SelectWithSearch
                                users={clientOptions}
                                value={selectedClients}
                                onChange={setSelectedClients}
                                placeholder={t('newsletters', 'search_clients')}
                            />
                        </div>
                    </div>
                )}

                <div className="flex items-center justify-end gap-3">
                    <span className="text-sm text-muted-foreground">
                        {t('newsletters', 'recipients_dedup_note')
                            .replace(':profiles', String(recipients.length))
                            .replace(':unique', String(new Set(recipients.map((r) => r.phone)).size))}
                    </span>
                    <Button onClick={handleSend} disabled={recipients.length === 0 || sending}>
                        <Send className="mr-2 h-4 w-4" />
                        {t('newsletters', 'send_to_recipients')}
                    </Button>
                </div>
            </DialogContent>
        </Dialog>
    );
}
