import { Head, Link, router, useHttp } from '@inertiajs/react';
import { ArrowLeft, Bot, Send, Trash2, User } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { DeleteConfirmModal } from '@/components/delete-confirm-modal';
import { Button } from '@/components/ui/button';
import AppLayout from '@/layouts/app-layout';
import type { BreadcrumbItem } from '@/types';

type Message = {
    id: number;
    role: 'user' | 'assistant';
    content: string;
    created_at: string;
};

type Course = { id: number; title: string; slug: string; description: string | null };
type Props = { course: Course; messages: Message[]; lessonTitles: string[] };

export default function CourseChat({ course, messages: initialMessages, lessonTitles }: Props) {
    const [messages, setMessages] = useState<Message[]>(initialMessages);
    const [input, setInput] = useState('');
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const bottomRef = useRef<HTMLDivElement>(null);
    const inputRef = useRef<HTMLTextAreaElement>(null);
    const http = useHttp();

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

    function send() {
        const content = input.trim();
        if (!content || loading) return;

        const optimistic: Message = {
            id: Date.now(),
            role: 'user',
            content,
            created_at: new Date().toISOString(),
        };

        setMessages((prev) => [...prev, optimistic]);
        setInput('');
        setLoading(true);
        setError(null);

        http.post(
            `/courses/${course.slug}/chat`,
            { message: content },
            {
                onSuccess: (response: Message) => {
                    setMessages((prev) => [...prev, response]);
                    setLoading(false);
                    inputRef.current?.focus();
                },
                onError: (err: Record<string, string> | { message?: string }) => {
                    setLoading(false);
                    setError('message' in err ? (err.message ?? 'Terjadi kesalahan.') : 'Terjadi kesalahan.');
                    setMessages((prev) => prev.filter((m) => m.id !== optimistic.id));
                },
            },
        );
    }

    const [showClearConfirm, setShowClearConfirm] = useState(false);

    function clearChat() {
        router.delete(`/courses/${course.slug}/chat`, {
            onSuccess: () => setMessages([]),
        });
    }

    function handleKeyDown(e: React.KeyboardEvent) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            send();
        }
    }

    const breadcrumbs: BreadcrumbItem[] = [
        { title: 'Kelas', href: '/courses' },
        { title: course.title, href: `/courses/${course.slug}` },
        { title: 'AI Assistant', href: '#' },
    ];

    return (
        <>
            <Head title={`AI Assistant — ${course.title}`} />

            <div className="flex h-full flex-col">
                {/* Header */}
                <div className="flex items-center gap-3 border-b px-4 py-3">
                    <Link
                        href={`/courses/${course.slug}`}
                        className="rounded-md p-1 text-muted-foreground hover:text-foreground"
                    >
                        <ArrowLeft className="h-4 w-4" />
                    </Link>
                    <div className="flex h-8 w-8 items-center justify-center rounded-full bg-primary/10">
                        <Bot className="h-4 w-4 text-primary" />
                    </div>
                    <div className="flex-1 min-w-0">
                        <p className="font-semibold text-sm">AI Assistant</p>
                        <p className="truncate text-xs text-muted-foreground">{course.title}</p>
                    </div>
                    {messages.length > 0 && (
                        <button
                            onClick={() => setShowClearConfirm(true)}
                            className="rounded-md p-1.5 text-muted-foreground hover:text-destructive"
                            title="Hapus riwayat"
                        >
                            <Trash2 className="h-4 w-4" />
                        </button>
                    )}
                </div>

                {/* Messages */}
                <div className="flex-1 overflow-y-auto px-4 py-4">
                    {messages.length === 0 && (
                        <div className="flex h-full flex-col items-center justify-center gap-4 text-center">
                            <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-primary/10">
                                <Bot className="h-8 w-8 text-primary" />
                            </div>
                            <div>
                                <p className="font-semibold">Halo! Saya AI Assistant</p>
                                <p className="mt-1 text-sm text-muted-foreground max-w-sm">
                                    Tanyakan apa saja tentang materi <strong>{course.title}</strong>. Saya siap membantu!
                                </p>
                            </div>
                            {lessonTitles.length > 0 && (
                                <div className="flex flex-wrap justify-center gap-2 max-w-md">
                                    {lessonTitles.slice(0, 4).map((title, i) => (
                                        <button
                                            key={i}
                                            onClick={() => setInput(`Jelaskan tentang: ${title}`)}
                                            className="rounded-lg border bg-muted/50 px-3 py-1.5 text-xs hover:bg-muted"
                                        >
                                            💡 {title}
                                        </button>
                                    ))}
                                </div>
                            )}
                        </div>
                    )}

                    <div className="flex flex-col gap-4 max-w-2xl mx-auto">
                        {messages.map((msg) => (
                            <div
                                key={msg.id}
                                className={`flex gap-3 ${msg.role === 'user' ? 'flex-row-reverse' : ''}`}
                            >
                                <div
                                    className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-full ${
                                        msg.role === 'assistant' ? 'bg-primary/10' : 'bg-muted'
                                    }`}
                                >
                                    {msg.role === 'assistant' ? (
                                        <Bot className="h-4 w-4 text-primary" />
                                    ) : (
                                        <User className="h-4 w-4 text-muted-foreground" />
                                    )}
                                </div>
                                <div
                                    className={`max-w-[80%] rounded-2xl px-4 py-2.5 text-sm leading-relaxed whitespace-pre-wrap ${
                                        msg.role === 'user'
                                            ? 'rounded-tr-sm bg-primary text-primary-foreground'
                                            : 'rounded-tl-sm bg-muted'
                                    }`}
                                >
                                    {msg.content}
                                </div>
                            </div>
                        ))}

                        {loading && (
                            <div className="flex gap-3">
                                <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary/10">
                                    <Bot className="h-4 w-4 text-primary" />
                                </div>
                                <div className="rounded-2xl rounded-tl-sm bg-muted px-4 py-3">
                                    <span className="flex gap-1">
                                        <span className="h-1.5 w-1.5 animate-bounce rounded-full bg-muted-foreground [animation-delay:0ms]" />
                                        <span className="h-1.5 w-1.5 animate-bounce rounded-full bg-muted-foreground [animation-delay:150ms]" />
                                        <span className="h-1.5 w-1.5 animate-bounce rounded-full bg-muted-foreground [animation-delay:300ms]" />
                                    </span>
                                </div>
                            </div>
                        )}

                        {error && (
                            <p className="text-center text-xs text-destructive">{error}</p>
                        )}

                        <div ref={bottomRef} />
                    </div>
                </div>

                {/* Input */}
                <div className="border-t p-4">
                    <div className="mx-auto flex max-w-2xl gap-2">
                        <textarea
                            ref={inputRef}
                            value={input}
                            onChange={(e) => setInput(e.target.value)}
                            onKeyDown={handleKeyDown}
                            placeholder="Tanyakan sesuatu... (Enter untuk kirim, Shift+Enter untuk baris baru)"
                            rows={1}
                            disabled={loading}
                            className="border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 flex-1 resize-none rounded-xl border bg-transparent px-3 py-2.5 text-sm outline-none focus-visible:ring-[3px] disabled:opacity-50"
                            style={{ maxHeight: '120px', overflowY: 'auto' }}
                            onInput={(e) => {
                                const el = e.currentTarget;
                                el.style.height = 'auto';
                                el.style.height = el.scrollHeight + 'px';
                            }}
                        />
                        <Button
                            onClick={send}
                            disabled={!input.trim() || loading}
                            size="icon"
                            className="shrink-0 self-end rounded-xl"
                        >
                            <Send className="h-4 w-4" />
                        </Button>
                    </div>
                    <p className="mx-auto mt-1.5 max-w-2xl text-center text-xs text-muted-foreground">
                        AI dapat membuat kesalahan. Selalu verifikasi informasi penting.
                    </p>
                </div>
            </div>

            <DeleteConfirmModal
                open={showClearConfirm}
                onClose={() => setShowClearConfirm(false)}
                onConfirm={() => { clearChat(); setShowClearConfirm(false); }}
                title="Hapus Semua Riwayat Chat?"
                description="Semua percakapan dengan AI akan dihapus permanen."
                confirmLabel="Hapus Semua"
            />
        </>
    );
}

CourseChat.layout = (page: React.ReactNode) => {
    const props = (page as React.ReactElement).props as Props;
    const breadcrumbs: BreadcrumbItem[] = [
        { title: 'Kelas', href: '/courses' },
        { title: props.course.title, href: `/courses/${props.course.slug}` },
        { title: 'AI Assistant', href: '#' },
    ];
    return <AppLayout breadcrumbs={breadcrumbs}>{page}</AppLayout>;
};
