import { useState, useEffect, useMemo } from 'react';
import {
    Loader2,
    Mail,
    Send,
    Sparkles,
    FileText,
    Eye,
    Edit3,
    User,
    Building2,
    Clock,
    Paperclip,
    X,
    ChevronDown,
    CheckCircle2,
    AlertCircle,
    Wand2,
    History,
    Star,
    Copy,
    Users,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Switch } from '@/components/ui/switch';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from '@/components/ui/popover';
import {
    Tooltip,
    TooltipContent,
    TooltipProvider,
    TooltipTrigger,
} from '@/components/ui/tooltip';
import {
    Tabs,
    TabsContent,
    TabsList,
    TabsTrigger,
} from '@/components/ui/tabs';
import { ScrollArea } from '@/components/ui/scroll-area';
import { supabase } from '@/integrations/supabase/client';
import { useEmailTemplates, replaceTemplateVariables } from '@/hooks/useEmailTemplates';
import { useBusiness } from '@/hooks/useBusiness';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';

interface Contact {
    id: string;
    first_name: string;
    last_name: string;
    email: string;
    phone?: string | null;
    company?: string | null;
}

interface SendEmailDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    contact: Contact;
    defaultSubject?: string;
    defaultBody?: string;
}

type EditorMode = 'compose' | 'preview';

const VARIABLE_TOKENS = [
    { token: '{{first_name}}', label: 'First Name', icon: User },
    { token: '{{last_name}}', label: 'Last Name', icon: User },
    { token: '{{company}}', label: 'Company', icon: Building2 },
    { token: '{{business_name}}', label: 'Your Business', icon: Building2 },
];

const QUICK_RESPONSES = [
    { label: 'Following up', text: "I wanted to follow up on our previous conversation." },
    { label: 'Thank you', text: "Thank you for your time today." },
    { label: 'Next steps', text: "Here are the next steps we discussed:" },
    { label: 'Schedule call', text: "Would you be available for a quick call this week?" },
];

export function SendEmailDialog({
    open,
    onOpenChange,
    contact,
    defaultSubject = '',
    defaultBody = '',
}: SendEmailDialogProps) {
    const { templates, isLoading: isLoadingTemplates } = useEmailTemplates();
    const { business } = useBusiness();

    const [isSending, setIsSending] = useState(false);
    const [editorMode, setEditorMode] = useState<EditorMode>('compose');

    // Email Field State
    const [subject, setSubject] = useState(defaultSubject);
    const [body, setBody] = useState(defaultBody);
    const [cc, setCc] = useState('');
    const [bcc, setBcc] = useState('');
    const [showCcBcc, setShowCcBcc] = useState(false);

    const [scheduleEnabled, setScheduleEnabled] = useState(false);
    const [showVariables, setShowVariables] = useState(false);
    const [recentlySent, setRecentlySent] = useState(false);

    const activeTemplates = useMemo(
        () => templates.filter(t => t.is_active),
        [templates]
    );

    // Reset state when dialog opens
    useEffect(() => {
        if (open) {
            setSubject(defaultSubject);
            setBody(defaultBody);
            setCc('');
            setBcc('');
            setShowCcBcc(false);
            setEditorMode('compose');
            setScheduleEnabled(false);
            setRecentlySent(false);
        }
    }, [open, defaultSubject, defaultBody]);

    // Process preview with variables replaced
    const previewContent = useMemo(() => ({
        subject: replaceTemplateVariables(subject, business, contact),
        body: replaceTemplateVariables(body, business, contact),
    }), [subject, body, business, contact]);

    // Character count and validation
    const validation = useMemo(() => {
        const subjectLength = subject.trim().length;
        const bodyLength = body.trim().length;
        const hasVariables = /\{\{.*?\}\}/.test(subject) || /\{\{.*?\}\}/.test(body);

        return {
            isValid: subjectLength > 0 && bodyLength > 0,
            subjectLength,
            bodyLength,
            hasVariables,
            warnings: [
                subjectLength > 100 && 'Subject line is quite long',
                bodyLength > 5000 && 'Email body is very long',
            ].filter(Boolean) as string[],
        };
    }, [subject, body]);

    const applyTemplate = (templateId: string) => {
        const template = templates.find(t => t.id === templateId);
        if (template) {
            setSubject(template.subject);
            setBody(template.body);
            toast.success(`Template "${template.name}" applied`);
        }
    };

    const insertVariable = (token: string) => {
        const textarea = document.getElementById('email-body') as HTMLTextAreaElement;
        if (textarea) {
            const start = textarea.selectionStart;
            const end = textarea.selectionEnd;
            const newBody = body.substring(0, start) + token + body.substring(end);
            setBody(newBody);
            setTimeout(() => {
                textarea.focus();
                textarea.setSelectionRange(start + token.length, start + token.length);
            }, 0);
        } else {
            setBody(prev => prev + token);
        }
        setShowVariables(false);
    };

    const insertQuickResponse = (text: string) => {
        setBody(prev => prev ? `${prev}\n\n${text}` : text);
    };

    const handleSend = async () => {
        if (!validation.isValid) {
            toast.error('Please fill in both subject and message');
            return;
        }

        setIsSending(true);
        try {
            const { data, error } = await supabase.functions.invoke('send-email', {
                body: {
                    to: contact.email,
                    cc: cc.trim() || undefined,
                    bcc: bcc.trim() || undefined,
                    subject: previewContent.subject,
                    body: previewContent.body,
                    contactId: contact.id,
                    scheduled: scheduleEnabled ? new Date().toISOString() : undefined,
                },
            });

            if (error) throw error;

            if (data.success) {
                setRecentlySent(true);
                toast.success(
                    <div className="flex items-center gap-2">
                        <CheckCircle2 className="h-4 w-4 text-green-500" />
                        <span>Email sent to {contact.first_name}</span>
                    </div>
                );

                setTimeout(() => {
                    onOpenChange(false);
                }, 1500);
            } else {
                throw new Error(data.error || 'Failed to send email');
            }
        } catch (error: any) {
            toast.error(error.message || 'Failed to send email');
        } finally {
            setIsSending(false);
        }
    };

    const handleCopyToClipboard = () => {
        const text = `Subject: ${previewContent.subject}\n\n${previewContent.body}`;
        navigator.clipboard.writeText(text);
        toast.success('Email copied to clipboard');
    };

    const contactInitials = `${contact.first_name?.[0] || ''}${contact.last_name?.[0] || ''}`.toUpperCase();

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="max-w-4xl p-0 gap-0 overflow-hidden">
                {/* Success Overlay */}
                {recentlySent && (
                    <div className="absolute inset-0 z-50 flex items-center justify-center bg-background/95 backdrop-blur-sm">
                        <div className="flex flex-col items-center gap-3 animate-in fade-in zoom-in duration-300">
                            <div className="h-16 w-16 rounded-full bg-green-500/10 flex items-center justify-center">
                                <CheckCircle2 className="h-8 w-8 text-green-500" />
                            </div>
                            <h3 className="text-lg font-semibold">Email Sent!</h3>
                            <p className="text-sm text-muted-foreground">
                                Your message is on its way to {contact.first_name}
                            </p>
                        </div>
                    </div>
                )}

                {/* Header */}
                <DialogHeader className="p-4 pb-0">
                    <div className="flex items-start justify-between">
                        <div className="flex items-center gap-3">
                            <div className="h-10 w-10 rounded-full bg-gradient-to-br from-blue-500 to-blue-600 flex items-center justify-center text-white font-medium text-sm">
                                {contactInitials || <Mail className="h-4 w-4" />}
                            </div>
                            <div>
                                <DialogTitle className="text-base">
                                    New Email to {contact.first_name} {contact.last_name}
                                </DialogTitle>
                                <div className="flex items-center gap-2 mt-0.5">
                                    <p className="text-sm text-muted-foreground">
                                        {contact.email}
                                    </p>
                                    {contact.company && (
                                        <>
                                            <span className="text-muted-foreground/30">•</span>
                                            <span className="text-xs text-muted-foreground">{contact.company}</span>
                                        </>
                                    )}
                                </div>
                            </div>
                        </div>

                        {/* Mode Toggle */}
                        <Tabs value={editorMode} onValueChange={(v) => setEditorMode(v as EditorMode)}>
                            <TabsList className="h-8">
                                <TabsTrigger value="compose" className="text-xs px-3 gap-1.5">
                                    <Edit3 className="h-3 w-3" />
                                    Compose
                                </TabsTrigger>
                                <TabsTrigger value="preview" className="text-xs px-3 gap-1.5">
                                    <Eye className="h-3 w-3" />
                                    Preview
                                </TabsTrigger>
                            </TabsList>
                        </Tabs>
                    </div>
                </DialogHeader>

                <Separator className="my-4" />

                {/* Main Content Area */}
                <div className="flex flex-1 min-h-0">
                    {/* Left: Editor/Preview */}
                    <div className="flex-1 flex flex-col min-w-0">
                        {editorMode === 'compose' ? (
                            <div className="flex-1 flex flex-col p-4 pt-0 space-y-4">

                                {/* CC/BCC Toggle Section */}
                                <div className="space-y-3">
                                    <div className="flex items-center justify-end">
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            onClick={() => setShowCcBcc(!showCcBcc)}
                                            className={cn("h-6 text-xs gap-1", showCcBcc ? "text-primary" : "text-muted-foreground")}
                                        >
                                            <Users className="h-3 w-3" />
                                            {showCcBcc ? 'Hide Cc/Bcc' : 'Add Cc/Bcc'}
                                        </Button>
                                    </div>

                                    {showCcBcc && (
                                        <div className="grid gap-3 animate-in slide-in-from-top-2 duration-200">
                                            <div className="grid gap-1">
                                                <Label htmlFor="cc" className="text-xs font-medium text-muted-foreground">Cc</Label>
                                                <Input
                                                    id="cc"
                                                    value={cc}
                                                    onChange={(e) => setCc(e.target.value)}
                                                    placeholder="comma, separated, emails"
                                                    className="h-8 text-sm"
                                                />
                                            </div>
                                            <div className="grid gap-1">
                                                <Label htmlFor="bcc" className="text-xs font-medium text-muted-foreground">Bcc</Label>
                                                <Input
                                                    id="bcc"
                                                    value={bcc}
                                                    onChange={(e) => setBcc(e.target.value)}
                                                    placeholder="comma, separated, emails"
                                                    className="h-8 text-sm"
                                                />
                                            </div>
                                        </div>
                                    )}
                                </div>

                                {/* Subject */}
                                <div className="space-y-1.5">
                                    <div className="flex items-center justify-between">
                                        <Label htmlFor="email-subject" className="text-xs font-medium">
                                            Subject
                                        </Label>
                                        <span className={cn(
                                            "text-[10px]",
                                            validation.subjectLength > 100 ? "text-amber-500" : "text-muted-foreground"
                                        )}>
                                            {validation.subjectLength}/100
                                        </span>
                                    </div>
                                    <Input
                                        id="email-subject"
                                        value={subject}
                                        onChange={(e) => setSubject(e.target.value)}
                                        placeholder="What's this email about?"
                                        className="h-9"
                                    />
                                </div>

                                {/* Body */}
                                <div className="flex-1 flex flex-col space-y-1.5 min-h-0">
                                    <div className="flex items-center justify-between">
                                        <Label htmlFor="email-body" className="text-xs font-medium">
                                            Message
                                        </Label>
                                        <div className="flex items-center gap-2">
                                            <Popover open={showVariables} onOpenChange={setShowVariables}>
                                                <PopoverTrigger asChild>
                                                    <Button variant="ghost" size="sm" className="h-6 px-2 text-xs gap-1">
                                                        <Wand2 className="h-3 w-3" />
                                                        Variables
                                                    </Button>
                                                </PopoverTrigger>
                                                <PopoverContent align="end" className="w-56 p-2">
                                                    <div className="space-y-1">
                                                        <p className="text-xs font-medium text-muted-foreground px-2 py-1">
                                                            Insert personalization
                                                        </p>
                                                        {VARIABLE_TOKENS.map((v) => (
                                                            <Button
                                                                key={v.token}
                                                                variant="ghost"
                                                                size="sm"
                                                                className="w-full justify-start gap-2 h-8 text-xs"
                                                                onClick={() => insertVariable(v.token)}
                                                            >
                                                                <v.icon className="h-3 w-3 text-muted-foreground" />
                                                                {v.label}
                                                                <code className="ml-auto text-[10px] text-muted-foreground">
                                                                    {v.token}
                                                                </code>
                                                            </Button>
                                                        ))}
                                                    </div>
                                                </PopoverContent>
                                            </Popover>

                                            <span className="text-[10px] text-muted-foreground">
                                                {validation.bodyLength} chars
                                            </span>
                                        </div>
                                    </div>

                                    <Textarea
                                        id="email-body"
                                        value={body}
                                        onChange={(e) => setBody(e.target.value)}
                                        placeholder="Write your message here..."
                                        className="flex-1 min-h-[200px] resize-none text-sm leading-relaxed"
                                    />

                                    {/* Quick Responses */}
                                    <div className="flex items-center gap-1.5 flex-wrap pt-1">
                                        <span className="text-[10px] text-muted-foreground mr-1">Quick add:</span>
                                        {QUICK_RESPONSES.map((qr) => (
                                            <Button
                                                key={qr.label}
                                                variant="outline"
                                                size="sm"
                                                className="h-6 px-2 text-[10px]"
                                                onClick={() => insertQuickResponse(qr.text)}
                                            >
                                                {qr.label}
                                            </Button>
                                        ))}
                                    </div>
                                </div>
                            </div>
                        ) : (
                            /* Preview Mode */
                            <ScrollArea className="flex-1 p-4 pt-0">
                                <div className="rounded-lg border bg-muted/30 p-4 space-y-4">
                                    <div className="grid gap-2 text-sm">
                                        <div className="grid grid-cols-[60px_1fr] gap-2">
                                            <span className="text-muted-foreground text-xs uppercase tracking-wider pt-0.5">To</span>
                                            <span className="font-medium">{contact.email}</span>
                                        </div>
                                        {cc && (
                                            <div className="grid grid-cols-[60px_1fr] gap-2">
                                                <span className="text-muted-foreground text-xs uppercase tracking-wider pt-0.5">Cc</span>
                                                <span className="text-muted-foreground">{cc}</span>
                                            </div>
                                        )}
                                        {bcc && (
                                            <div className="grid grid-cols-[60px_1fr] gap-2">
                                                <span className="text-muted-foreground text-xs uppercase tracking-wider pt-0.5">Bcc</span>
                                                <span className="text-muted-foreground">{bcc}</span>
                                            </div>
                                        )}
                                        <div className="grid grid-cols-[60px_1fr] gap-2">
                                            <span className="text-muted-foreground text-xs uppercase tracking-wider pt-0.5">Subject</span>
                                            <span className="font-medium">
                                                {previewContent.subject || (
                                                    <span className="text-muted-foreground italic">No subject</span>
                                                )}
                                            </span>
                                        </div>
                                    </div>

                                    <Separator />

                                    <div className="prose prose-sm max-w-none">
                                        {previewContent.body ? (
                                            <p className="whitespace-pre-wrap text-sm leading-relaxed">
                                                {previewContent.body}
                                            </p>
                                        ) : (
                                            <p className="text-muted-foreground italic">No message content</p>
                                        )}
                                    </div>

                                    {validation.hasVariables && (
                                        <div className="flex items-center gap-2 text-xs text-amber-600 bg-amber-500/10 rounded-md px-3 py-2 mt-4">
                                            <Sparkles className="h-3.5 w-3.5" />
                                            Variables will be replaced with actual values
                                        </div>
                                    )}
                                </div>

                                <Button
                                    variant="ghost"
                                    size="sm"
                                    className="mt-3 gap-2"
                                    onClick={handleCopyToClipboard}
                                >
                                    <Copy className="h-3.5 w-3.5" />
                                    Copy to clipboard
                                </Button>
                            </ScrollArea>
                        )}
                    </div>

                    {/* Right Sidebar: Templates */}
                    <div className="w-64 border-l bg-muted/20 flex flex-col">
                        <div className="p-3 border-b">
                            <h4 className="text-xs font-semibold flex items-center gap-2">
                                <FileText className="h-3.5 w-3.5" />
                                Email Templates
                            </h4>
                        </div>

                        <ScrollArea className="flex-1">
                            <div className="p-2 space-y-1">
                                {isLoadingTemplates ? (
                                    <div className="flex items-center justify-center py-8">
                                        <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
                                    </div>
                                ) : activeTemplates.length === 0 ? (
                                    <div className="text-center py-8 px-4">
                                        <FileText className="h-8 w-8 mx-auto text-muted-foreground/50 mb-2" />
                                        <p className="text-xs text-muted-foreground">
                                            No templates available
                                        </p>
                                        <p className="text-[10px] text-muted-foreground mt-1">
                                            Create templates in Settings
                                        </p>
                                    </div>
                                ) : (
                                    activeTemplates.map((template) => (
                                        <button
                                            key={template.id}
                                            onClick={() => applyTemplate(template.id)}
                                            className={cn(
                                                "w-full text-left p-2.5 rounded-md transition-colors",
                                                "hover:bg-accent group"
                                            )}
                                        >
                                            <div className="flex items-start gap-2">
                                                <Star className="h-3.5 w-3.5 mt-0.5 text-amber-500 opacity-0 group-hover:opacity-100 transition-opacity" />
                                                <div className="flex-1 min-w-0">
                                                    <p className="text-xs font-medium truncate">
                                                        {template.name}
                                                    </p>
                                                    <p className="text-[10px] text-muted-foreground truncate mt-0.5">
                                                        {template.subject}
                                                    </p>
                                                </div>
                                            </div>
                                        </button>
                                    ))
                                )}
                            </div>
                        </ScrollArea>
                    </div>
                </div>

                {/* Footer */}
                <div className="border-t p-4 bg-muted/30">
                    <div className="flex items-center justify-between">
                        <div className="flex items-center gap-4">
                            {/* Schedule Toggle */}
                            <TooltipProvider>
                                <Tooltip>
                                    <TooltipTrigger asChild>
                                        <div className="flex items-center gap-2">
                                            <Switch
                                                id="schedule"
                                                checked={scheduleEnabled}
                                                onCheckedChange={setScheduleEnabled}
                                                disabled
                                            />
                                            <Label
                                                htmlFor="schedule"
                                                className="text-xs text-muted-foreground cursor-pointer"
                                            >
                                                <Clock className="h-3 w-3 inline mr-1" />
                                                Schedule
                                            </Label>
                                        </div>
                                    </TooltipTrigger>
                                    <TooltipContent>
                                        <p>Scheduling coming soon</p>
                                    </TooltipContent>
                                </Tooltip>
                            </TooltipProvider>

                            {/* Warnings */}
                            {validation.warnings.length > 0 && (
                                <div className="flex items-center gap-1.5 text-xs text-amber-600">
                                    <AlertCircle className="h-3.5 w-3.5" />
                                    {validation.warnings[0]}
                                </div>
                            )}
                        </div>

                        <div className="flex items-center gap-2">
                            <Button
                                variant="ghost"
                                onClick={() => onOpenChange(false)}
                                disabled={isSending}
                            >
                                Cancel
                            </Button>

                            <Button
                                onClick={handleSend}
                                disabled={isSending || !validation.isValid}
                                className="gap-2 min-w-[120px]"
                            >
                                {isSending ? (
                                    <>
                                        <Loader2 className="h-4 w-4 animate-spin" />
                                        Sending...
                                    </>
                                ) : (
                                    <>
                                        <Send className="h-4 w-4" />
                                        Send Email
                                    </>
                                )}
                            </Button>
                        </div>
                    </div>
                </div>
            </DialogContent>
        </Dialog>
    );
}