import React, { useState } from 'react';
import { router } from '@inertiajs/react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/Components/ui/dialog";
import { Button } from "@/Components/ui/button";
import { MessageSquareText, Mail, PhoneCall, MessageCircle, ExternalLink, Store, Loader2 } from 'lucide-react';
import { toast } from 'sonner';
import { useTranslation } from '@/hooks/useTranslation';

export default function ContactModal({ isOpen, onClose, seller, product = null }) {
    const { t } = useTranslation();
    const [isStartingChat, setIsStartingChat] = useState(false);

    if (!seller) return null;

    const options = seller.contact_options || {
        web_chat: true, email: false, phone: false, whatsapp: false, messenger: false
    };

    const getCleanWhatsApp = (number) => {
        if (!number) return '';
        return number.replace(/[^0-9]/g, '');
    };

    const handleWebChat = () => {
        setIsStartingChat(true);
        
        // --- CHANGED: Using user_id for Smart Chat Mapping ---
        router.post(route('chat.start'), { 
            user_id: seller.id, 
            product_id: product?.id || null 
        }, {
            preserveScroll: true,
            onSuccess: () => {
                setIsStartingChat(false);
                onClose();
            },
            onError: (errors) => {
                setIsStartingChat(false);
                toast.error(t(errors.error || "Could not start chat. You cannot message yourself."));
            }
        });
    };

    return (
        <Dialog open={isOpen} onOpenChange={(open) => !isStartingChat && onClose(open)}>
            <DialogContent className="max-w-md sm:rounded-2xl bg-card border-border/50 shadow-xl">
                <DialogHeader>
                    <DialogTitle className="flex items-center gap-2 text-xl">
                        <Store className="w-5 h-5 text-primary" /> 
                        {t('Contact :name', { name: seller.company_name || seller.name })}
                    </DialogTitle>
                    <DialogDescription>
                        {t('Choose your preferred method to reach out to this supplier.')}
                    </DialogDescription>
                </DialogHeader>

                <div className="py-4 space-y-3">
                    
                    {options.web_chat && (
                        <Button 
                            className="w-full justify-start h-14 text-base font-bold gap-3 shadow-md" 
                            onClick={handleWebChat}
                            disabled={isStartingChat}
                        >
                            {isStartingChat ? <Loader2 className="w-5 h-5 animate-spin" /> : <MessageSquareText className="w-5 h-5" />}
                            {isStartingChat ? t('Opening Chat...') : t('Chat on Platform')}
                        </Button>
                    )}

                    {options.whatsapp && seller.contact_whatsapp && (
                        <Button 
                            variant="outline" 
                            className="w-full justify-start h-14 text-base font-bold gap-3 border-green-500/30 text-green-600 hover:bg-green-500/10 hover:text-green-700 transition-colors"
                            asChild
                        >
                            <a href={`https://wa.me/${getCleanWhatsApp(seller.contact_whatsapp)}`} target="_blank" rel="noreferrer">
                                <MessageCircle className="w-5 h-5" />
                                {t('WhatsApp')}
                                <ExternalLink className="w-4 h-4 ml-auto opacity-50" />
                            </a>
                        </Button>
                    )}

                    {options.messenger && seller.contact_messenger && (
                        <Button 
                            variant="outline" 
                            className="w-full justify-start h-14 text-base font-bold gap-3 border-blue-500/30 text-blue-600 hover:bg-blue-500/10 hover:text-blue-700 transition-colors"
                            asChild
                        >
                            <a href={seller.contact_messenger} target="_blank" rel="noreferrer">
                                <MessageCircle className="w-5 h-5" />
                                {t('Messenger')}
                                <ExternalLink className="w-4 h-4 ml-auto opacity-50" />
                            </a>
                        </Button>
                    )}

                    {options.email && seller.contact_email && (
                        <Button 
                            variant="outline" 
                            className="w-full justify-start h-14 text-base font-bold gap-3"
                            asChild
                        >
                            <a href={`mailto:${seller.contact_email}`}>
                                <Mail className="w-5 h-5 text-muted-foreground" />
                                {t('Email: :email', { email: seller.contact_email })}
                            </a>
                        </Button>
                    )}

                    {options.phone && seller.contact_phone && (
                        <Button 
                            variant="outline" 
                            className="w-full justify-start h-14 text-base font-bold gap-3"
                            asChild
                        >
                            <a href={`tel:${seller.contact_phone.replace(/[^0-9+]/g, '')}`}>
                                <PhoneCall className="w-5 h-5 text-muted-foreground" />
                                {t('Call: :phone', { phone: seller.contact_phone })}
                            </a>
                        </Button>
                    )}

                    {!options.web_chat && (!options.whatsapp || !seller.contact_whatsapp) && (!options.messenger || !seller.contact_messenger) && (!options.email || !seller.contact_email) && (!options.phone || !seller.contact_phone) && (
                        <div className="text-center p-6 border border-dashed rounded-xl bg-muted/20 text-muted-foreground text-sm">
                            {t('This supplier has not enabled any direct contact methods.')}
                        </div>
                    )}
                </div>
            </DialogContent>
        </Dialog>
    );
}