import React, { useState, useRef, useEffect } from 'react';
import { usePage } from '@inertiajs/react'; // 🚀 Import usePage dari Inertia

interface Message {
    role: 'user' | 'assistant';
    text: string;
}

interface AIChatPopupProps {
    activeContractId?: string | number | null;
    activeContractName?: string;
}

export default function AIChatPopup({ activeContractId: propId, activeContractName: propName }: AIChatPopupProps) {
    // 🚀 Ambil data dari Inertia Props jika tidak dilempar lewat props manual
    const { props } = usePage();
    const pageContracts = (props as any).contracts?.data || (props as any).contracts || [];

    // Gunakan props manual jika ada, jika tidak ambil kontrak pertama dari halaman aktif
    const activeContractId = propId ?? (pageContracts.length > 0 ? pageContracts[0].id : null);
    const activeContractName = propName ?? (pageContracts.length > 0 ? pageContracts[0].docName : '');

    const [isOpen, setIsOpen] = useState(false);
    const [messages, setMessages] = useState<Message[]>([
        { role: 'assistant', text: 'Halo! Ada yang bisa saya bantu terkait dokumen kontrak Scuto Legal Anda?' }
    ]);
    const [input, setInput] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const chatEndRef = useRef<HTMLDivElement>(null);

    // State untuk kontrol ukuran & posisi dinamis
    const [dimensions, setDimensions] = useState({ w: 440, h: 600 });
    const [position, setPosition] = useState({ bottom: 96, right: 24 });
    const containerRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        if (activeContractName) {
            setMessages([
                {
                    role: 'assistant',
                    text: `Halo! Saya siap membantu menganalisis dokumen "${activeContractName}". Ada yang ingin Anda tanyakan seputar kontrak ini?`
                }
            ]);
        }
    }, [activeContractName]);

    useEffect(() => {
        chatEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, [messages, isLoading]);

    // Fungsi Handle Resize
    const handleResizeMouseDown = (e: React.MouseEvent) => {
        e.preventDefault();
        const startX = e.clientX;
        const startY = e.clientY;
        const startW = dimensions.w;
        const startH = dimensions.h;

        const handleMouseMove = (moveEvent: MouseEvent) => {
            const deltaX = moveEvent.clientX - startX;
            const deltaY = moveEvent.clientY - startY;

            const newW = Math.max(360, Math.min(800, startW - deltaX));
            const newH = Math.max(450, Math.min(750, startH - deltaY));

            setDimensions({ w: newW, h: newH });
        };

        const handleMouseUp = () => {
            window.removeEventListener('mousemove', handleMouseMove);
            window.removeEventListener('mouseup', handleMouseUp);
        };

        window.addEventListener('mousemove', handleMouseMove);
        window.addEventListener('mouseup', handleMouseUp);
    };

    const handleSendMessage = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!input.trim() || isLoading) return;

        const userQuery = input;
        setMessages((prev) => [...prev, { role: 'user', text: userQuery }]);
        setInput('');
        setIsLoading(true);

        try {
            // 🚀 PERBAIKAN VITE ENV: Tambahkan VITE_ agar dibaca oleh Vite
            const webhookUrl = import.meta.env.VITE_N8N_CHAT_BOT || import.meta.env.N8N_CHAT_BOT || '';

            if (!webhookUrl) {
                console.error("URL Webhook N8N belum dikonfigurasi di file .env!");
            }

            const response = await fetch(webhookUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    message: userQuery,
                    contract_id: activeContractId
                }),
            });

            if (!response.ok) throw new Error('Gagal terhubung ke n8n');
            const data = await response.json();

            setMessages((prev) => [
                ...prev,
                { role: 'assistant', text: data.output || data.message || 'Maaf, saya tidak dapat memproses jawaban.' }
            ]);
        } catch (error) {
            console.error("Error AI Chat:", error);
            setMessages((prev) => [
                ...prev,
                { role: 'assistant', text: 'Koneksi ke Scuto Legal AI terputus. Mohon coba lagi beberapa saat lagi.' }
            ]);
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <div className="fixed bottom-6 right-6 z-50 font-sans text-slate-200">
            {!isOpen && (
                <button
                    onClick={() => setIsOpen(true)}
                    className="flex h-14 w-14 items-center justify-center rounded-full bg-[#FF5722] text-white shadow-lg transition-transform hover:scale-105 active:scale-95"
                >
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" /></svg>
                </button>
            )}

            {/* JENDELA POP-UP CHAT */}
            {isOpen && (
                <div
                    ref={containerRef}
                    style={{
                        width: `${dimensions.w}px`,
                        height: `${dimensions.h}px`,
                        bottom: `${position.bottom}px`,
                        right: `${position.right}px`
                    }}
                    className="flex flex-col rounded-2xl border border-slate-800 bg-[#0d1527] shadow-2xl fixed z-50 overflow-hidden select-none"
                >
                    {/* HANDLE RESIZE KIRI ATAS */}
                    <div
                        onMouseDown={handleResizeMouseDown}
                        className="absolute top-0 left-0 w-4 h-4 cursor-nwse-resize z-50 bg-transparent"
                        title="Tarik untuk mengubah ukuran"
                    />

                    {/* Header */}
                    <div className="flex items-center justify-between border-b border-slate-800 p-4 bg-[#0d1527] select-none">
                        <div className="flex items-center gap-2 pl-2">
                            <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-[#FF5722]/10 text-[#FF5722]">
                                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 8V4H8" /><rect width="16" height="12" x="4" y="8" rx="2" /><path d="M2 14h2" /><path d="M20 14h2" /><path d="M15 13v2" /><path d="M9 13v2" /></svg>
                            </div>
                            <div>
                                <h3 className="text-sm font-semibold text-white">Scuto Legal AI</h3>
                                <p className="text-xs text-emerald-400 flex items-center gap-1">
                                    <span className="h-1.5 w-1.5 rounded-full bg-emerald-400 inline-block animate-pulse"></span>
                                    Online
                                </p>
                            </div>
                        </div>
                        <button
                            onClick={() => setIsOpen(false)}
                            className="rounded-lg p-1 text-slate-400 hover:bg-slate-800 hover:text-white transition"
                        >
                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
                        </button>
                    </div>

                    {/* Area Pesan Chat */}
                    <div className="flex-1 overflow-y-auto p-4 space-y-4 [&::-webkit-scrollbar]:w-1.5 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-slate-800">
                        {messages.map((msg, index) => (
                            <div
                                key={index}
                                className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}
                            >
                                <div
                                    className={`max-w-[85%] rounded-2xl px-4 py-2.5 text-sm leading-relaxed ${msg.role === 'user'
                                        ? 'bg-[#FF5722] text-white rounded-tr-none'
                                        : 'bg-slate-800 text-slate-100 rounded-tl-none border border-slate-700'
                                        }`}
                                >
                                    {msg.text}
                                </div>
                            </div>
                        ))}

                        {/* Indikator typing */}
                        {isLoading && (
                            <div className="flex justify-start">
                                <div className="bg-slate-800 border border-slate-700 text-slate-400 max-w-[80%] rounded-2xl rounded-tl-none px-4 py-2.5 text-sm flex items-center gap-1">
                                    <span className="h-2 w-2 rounded-full bg-slate-500 animate-bounce"></span>
                                    <span className="h-2 w-2 rounded-full bg-slate-500 animate-bounce [animation-delay:0.2s]"></span>
                                    <span className="h-2 w-2 rounded-full bg-slate-500 animate-bounce [animation-delay:0.4s]"></span>
                                </div>
                            </div>
                        )}
                        <div ref={chatEndRef} />
                    </div>

                    {/* Form Input Chat */}
                    <form onSubmit={handleSendMessage} className="border-t border-slate-800 p-3 flex gap-2 bg-[#0d1527]">
                        <input
                            type="text"
                            value={input}
                            onChange={(e) => setInput(e.target.value)}
                            disabled={isLoading}
                            placeholder={isLoading ? "AI sedang berpikir..." : "Tanyakan sesuatu tentang kontrak..."}
                            className="flex-1 rounded-xl bg-slate-900 border border-slate-800 px-4 py-2 text-sm text-white placeholder-slate-500 focus:border-[#FF5722] focus:outline-none disabled:opacity-50"
                        />
                        <button
                            type="submit"
                            disabled={isLoading}
                            className="flex items-center justify-center rounded-xl bg-[#FF5722] p-2 text-white hover:bg-[#e64a19] transition disabled:opacity-50"
                        >
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>
                        </button>
                    </form>

                </div>
            )}
        </div>
    );
}