import React, { useState } from 'react';
import { Link, usePage } from '@inertiajs/react';
import axios from 'axios';
import { toast } from 'sonner';
import { useChat } from '@/hooks/useChat';
import { Avatar, AvatarFallback, AvatarImage } from "@/Components/ui/avatar";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Badge } from "@/Components/ui/badge";
import { 
    User, ArrowLeft, Send, Package, ExternalLink, 
    Clock, CreditCard, Truck, CheckCircle2, AlertCircle, ShoppingBag, Undo2, XCircle,
    Sparkles, Loader2
} from 'lucide-react';
import ChatBubble from './ChatBubble';
import { useTranslation } from '@/hooks/useTranslation';

export default function ChatWindow({ activeChat, authUser, onBack }) {
    const { t, locale } = useTranslation();
    const { appSettings } = usePage().props;
    const { messages, sendMessage, messagesEndRef } = useChat(activeChat, authUser);
    
    const [body, setBody] = useState("");
    const [isGeneratingAi, setIsGeneratingAi] = useState(false);

    // --- CHECK IF CURRENT USER IS THE SELLER IN THIS CHAT (FIXED TYPE MISMATCH) ---
    const isSellerInChat = Number(authUser.id) === Number(activeChat?.seller_id);

    const handleSubmit = (e) => {
        e.preventDefault();
        sendMessage(body);
        setBody("");
    };

    // --- AI Suggestion Handler ---
    const handleAiGenerate = async () => {
        setIsGeneratingAi(true);
        toast.loading(t('AI is thinking...'), { id: 'ai-gen' });
        
        try {
            const res = await axios.post(route('chat.ai.reply', activeChat.id));
            if (res.data.success) {
                setBody(res.data.reply); // Paste the AI reply directly into the input box
                toast.success(t('AI draft generated! Review before sending.'), { id: 'ai-gen' });
            }
        } catch (err) {
            toast.error(err.response?.data?.message || t('Failed to generate reply.'), { id: 'ai-gen' });
        } finally {
            setIsGeneratingAi(false);
        }
    };

    const getStatusUI = (status, isRefundRequested) => {
        if (isRefundRequested && status !== 'refunded') {
            return { icon: AlertCircle, color: 'bg-orange-500/10 text-orange-600 border-orange-500/20', label: t('Refund Pending') };
        }

        switch(status) {
            case 'pending':
                return { icon: CreditCard, color: 'bg-zinc-500/10 text-zinc-600 border-zinc-500/20', label: t('Awaiting Payment') };
            case 'processing':
                return { icon: Package, color: 'bg-blue-500/10 text-blue-600 border-blue-500/20', label: t('Processing Order') };
            case 'shipped':
                return { icon: Truck, color: 'bg-indigo-500/10 text-indigo-600 border-indigo-500/20', label: t('Shipped') };
            case 'completed':
                return { icon: CheckCircle2, color: 'bg-green-500/10 text-green-600 border-green-500/20', label: t('Completed') };
            case 'cancelled':
                return { icon: XCircle, color: 'bg-red-500/10 text-red-600 border-red-500/20', label: t('Cancelled') };
            case 'refunded':
                return { icon: Undo2, color: 'bg-purple-500/10 text-purple-600 border-purple-500/20', label: t('Refunded') };
            default:
                return { icon: Clock, color: 'bg-muted text-muted-foreground border-border', label: status };
        }
    };

    // --- Helper to format the Date Divider ---
    const formatDateDivider = (dateString) => {
        const date = new Date(dateString);
        const today = new Date();
        const yesterday = new Date(today);
        yesterday.setDate(yesterday.getDate() - 1);

        if (date.toDateString() === today.toDateString()) {
            return t('Today');
        } else if (date.toDateString() === yesterday.toDateString()) {
            return t('Yesterday');
        } else {
            return date.toLocaleDateString(locale || 'en', { 
                day: 'numeric', 
                month: 'short', 
                year: 'numeric' 
            });
        }
    };

    const order = activeChat?.latest_order;
    const orderStatus = order ? getStatusUI(order.status, order.is_refund_requested) : null;

    return (
        /* STRICT FLEXBOX CONSTRAINTS: min-h-0 prevents the container from stretching out of bounds */
        <div className="flex flex-col h-full w-full bg-background relative overflow-hidden min-h-0">
            
            {/* Header: User Info (shrink-0 forces it to stay fixed) */}
            <div className="h-16 border-b flex items-center px-4 sm:px-6 bg-card shrink-0 shadow-sm z-20">
                <Button variant="ghost" size="icon" className="md:hidden mr-2 shrink-0" onClick={onBack}>
                    <ArrowLeft className="w-5 h-5" />
                </Button>
                <Avatar className="w-10 h-10 border bg-muted mr-3 shrink-0 shadow-sm">
                    <AvatarImage src={activeChat?.other_user?.avatar_path ? `/storage/${activeChat.other_user.avatar_path}` : ''} />
                    <AvatarFallback><User className="w-5 h-5 text-muted-foreground"/></AvatarFallback>
                </Avatar>
                <div className="flex-1 min-w-0">
                    <h3 className="font-bold text-sm truncate">{activeChat?.other_user?.name}</h3>
                </div>
            </div>

            {/* Context Banner (shrink-0 forces it to stay fixed) */}
            {activeChat?.product && (
                <div className="bg-muted/10 border-b p-3 sm:p-4 flex items-center gap-3 shrink-0 shadow-sm z-10">
                    <Link href={route('product.view', `${activeChat.product.slug}_${activeChat.product.id}`)} className="shrink-0 group">
                        <div className="w-12 h-12 sm:w-14 sm:h-14 rounded-lg border bg-white flex items-center justify-center overflow-hidden shadow-sm group-hover:border-primary transition-colors">
                            {activeChat.product.images?.[0] ? (
                                <img src={`/storage/${activeChat.product.images[0].path}`} className="w-full h-full object-contain" />
                            ) : <ShoppingBag className="w-5 h-5 text-muted-foreground opacity-50"/>}
                        </div>
                    </Link>

                    <div className="flex-1 overflow-hidden min-w-0">
                        {order ? (
                            <div className="flex flex-col gap-1">
                                <div className="flex flex-wrap items-center gap-2">
                                    <span className="text-[10px] font-black text-muted-foreground uppercase tracking-widest">
                                        {t('Order')} #{order.order_number}
                                    </span>
                                    <Badge variant="outline" className={`px-1.5 py-0 text-[9px] font-bold uppercase tracking-wider flex items-center gap-1 ${orderStatus.color}`}>
                                        <orderStatus.icon className="w-3 h-3" /> {orderStatus.label}
                                    </Badge>
                                </div>

                                <Link href={route('product.view', `${activeChat.product.slug}_${activeChat.product.id}`)} className="text-sm font-bold truncate hover:text-primary transition-colors pr-2 block">
                                    {activeChat.product.title}
                                </Link>

                                {order.status === 'shipped' && order.tracking_number && (
                                    <div className="text-xs font-medium text-muted-foreground mt-0.5 flex items-center gap-1.5 truncate">
                                        <Truck className="w-3 h-3 shrink-0" />
                                        <span>{t('Tracking')}:</span> 
                                        <span className="font-mono truncate">{order.tracking_number}</span>
                                    </div>
                                )}
                            </div>
                        ) : (
                            <div className="flex flex-col justify-center h-full">
                                <p className="text-[10px] font-bold text-muted-foreground uppercase tracking-widest flex items-center gap-1 mb-0.5">
                                    <Package className="w-3 h-3" /> {t('Inquiring about')}
                                </p>
                                <Link href={route('product.view', `${activeChat.product.slug}_${activeChat.product.id}`)} className="text-sm font-bold truncate hover:text-primary transition-colors flex items-center justify-between group block">
                                    <span className="truncate">{activeChat.product.title}</span>
                                    <ExternalLink className="w-4 h-4 text-muted-foreground opacity-50 group-hover:opacity-100 group-hover:text-primary transition-all shrink-0 ml-2" />
                                </Link>
                            </div>
                        )}
                    </div>
                </div>
            )}

            {/* Chat History */}
            <div className="flex-1 overflow-y-auto p-4 sm:p-6 bg-slate-50/50 dark:bg-zinc-950/50 custom-scrollbar min-h-0 flex flex-col gap-4">
                {messages.map((msg, index) => {
                    const currentMsgDate = new Date(msg.created_at).toDateString();
                    const prevMsgDate = index > 0 ? new Date(messages[index - 1].created_at).toDateString() : null;
                    const showDateDivider = currentMsgDate !== prevMsgDate;

                    return (
                        <React.Fragment key={msg.id}>
                            {showDateDivider && (
                                <div className="flex justify-center my-4">
                                    <span className="bg-muted/70 text-muted-foreground text-[10px] font-bold uppercase tracking-widest px-3 py-1 rounded-full border shadow-sm">
                                        {formatDateDivider(msg.created_at)}
                                    </span>
                                </div>
                            )}

                            <ChatBubble 
                                message={msg} 
                                isMe={msg.sender_id === authUser.id} 
                                activeChat={activeChat}
                            />
                        </React.Fragment>
                    );
                })}
                <div ref={messagesEndRef} className="h-1 shrink-0" />
            </div>

            {/* Input Box Area */}
            <div className="p-4 bg-card border-t shrink-0">
                
                {/* AI Suggestion Button (Hidden for Buyers) */}
                {appSettings?.ai_chat_assistant && messages.length > 0 && isSellerInChat && (
                    <div className="flex justify-end mb-2">
                        <Button 
                            variant="secondary" 
                            size="sm" 
                            onClick={handleAiGenerate}
                            disabled={isGeneratingAi}
                            className="h-7 text-xs gap-1.5 bg-primary/10 text-primary hover:bg-primary/20 border border-primary/20 rounded-full transition-all shadow-sm"
                        >
                            {isGeneratingAi ? <Loader2 className="w-3 h-3 animate-spin" /> : <Sparkles className="w-3 h-3 fill-primary" />}
                            {isGeneratingAi ? t('Generating...') : t('AI Suggest Reply')}
                        </Button>
                    </div>
                )}

                <form onSubmit={handleSubmit} className="flex gap-2 relative">
                    <Input 
                        value={body}
                        onChange={(e) => setBody(e.target.value)}
                        placeholder={t('Write your message here...')} 
                        className="flex-1 rounded-full bg-muted/50 border-transparent focus-visible:ring-primary pl-4 pr-12 h-12"
                    />
                    <Button 
                        type="submit" 
                        size="icon" 
                        disabled={!body.trim()}
                        className="absolute right-1 top-1 h-10 w-10 rounded-full shadow-sm"
                    >
                        <Send className="w-4 h-4 ml-1" />
                    </Button>
                </form>
            </div>
        </div>
    );
}