import React, { useState, useEffect, useRef, useCallback } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Sparkles, Mic, MicOff, Send, RefreshCw, Bot, TrendingUp, Tag, Receipt, User as UserIcon } from "lucide-react";
import { api } from "@/lib/api";
import { useCompany } from "@/context/CompanyContext";
import { toast } from "sonner";
import ReactMarkdown from "react-markdown";

// Quick prompt suggestions
const SUGGESTIONS = [
    { icon: "💰", text: "Aaj ka profit kitna hai?" },
    { icon: "📦", text: "Which items are low in stock?" },
    { icon: "🏆", text: "Top 5 selling items this month" },
    { icon: "📅", text: "GST liability for this month" },
    { icon: "👥", text: "Best customers this month" },
    { icon: "💡", text: "Suggest one way to grow my business" },
];

export default function AiAssistant() {
    const { activeId } = useCompany();
    const [tab, setTab] = useState("chat");
    const [messages, setMessages] = useState([]);
    const [input, setInput] = useState("");
    const [thinking, setThinking] = useState(false);
    const sessionId = useRef(`web-${Date.now()}`);
    const listRef = useRef(null);

    // Voice
    const [recognizing, setRecognizing] = useState(false);
    const recogRef = useRef(null);

    // Insights
    const [insights, setInsights] = useState(null);
    const [insightsLoading, setInsightsLoading] = useState(false);

    // GST suggestion
    const [gstQuery, setGstQuery] = useState("");
    const [gstResult, setGstResult] = useState(null);
    const [gstLoading, setGstLoading] = useState(false);

    // Expense categorize
    const [expQuery, setExpQuery] = useState("");
    const [expAmount, setExpAmount] = useState("");
    const [expResult, setExpResult] = useState(null);
    const [expLoading, setExpLoading] = useState(false);

    useEffect(() => {
        if (listRef.current) listRef.current.scrollTop = listRef.current.scrollHeight;
    }, [messages, thinking]);

    const send = useCallback(async (text) => {
        const q = (text || "").trim();
        if (!q || thinking) return;
        setMessages((m) => [...m, { role: "user", text: q, ts: Date.now() }]);
        setInput("");
        setThinking(true);
        try {
            const { data } = await api.post("/ai/chat", { message: q, company_id: activeId, session_id: sessionId.current });
            setMessages((m) => [...m, { role: "assistant", text: data.reply, ts: Date.now() }]);
        } catch (e) {
            const msg = e.response?.data?.detail || "AI request failed";
            setMessages((m) => [...m, { role: "assistant", text: `⚠️ ${msg}`, ts: Date.now(), error: true }]);
            toast.error(msg);
        } finally { setThinking(false); }
    }, [thinking, activeId]);

    // Web Speech API
    const startVoice = () => {
        const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
        if (!SR) { toast.error("Voice not supported in this browser. Try Chrome."); return; }
        const r = new SR();
        r.lang = navigator.language?.startsWith("hi") ? "hi-IN" : "en-IN";
        r.interimResults = true;
        r.continuous = false;
        r.onstart = () => setRecognizing(true);
        r.onerror = (e) => { setRecognizing(false); toast.error(`Voice error: ${e.error}`); };
        r.onend = () => setRecognizing(false);
        r.onresult = (ev) => {
            const txt = Array.from(ev.results).map((r) => r[0].transcript).join("");
            setInput(txt);
            if (ev.results[0].isFinal) {
                setTimeout(() => send(txt), 100);
            }
        };
        try { r.start(); recogRef.current = r; }
        catch (err) { toast.error("Could not start voice"); console.warn(err); }
    };
    const stopVoice = () => { try { recogRef.current?.stop(); } catch (err) { console.debug("recog stop:", err?.message); } };

    const loadInsights = async () => {
        if (!activeId) return;
        setInsightsLoading(true);
        try {
            const { data } = await api.get("/ai/insights", { params: { company_id: activeId } });
            setInsights(data);
        } catch (e) { toast.error(e.response?.data?.detail || "Failed to generate insights"); }
        finally { setInsightsLoading(false); }
    };

    const suggestGst = async () => {
        if (!gstQuery.trim()) return;
        setGstLoading(true);
        try {
            const { data } = await api.post("/ai/suggest-gst", { description: gstQuery });
            setGstResult(data);
        } catch (e) { toast.error("AI request failed"); }
        finally { setGstLoading(false); }
    };

    const categorize = async () => {
        if (!expQuery.trim()) return;
        setExpLoading(true);
        try {
            const { data } = await api.post("/ai/categorize-expense", { description: expQuery, amount: parseFloat(expAmount) || 0 });
            setExpResult(data);
        } catch (e) { toast.error("AI request failed"); }
        finally { setExpLoading(false); }
    };

    return (
        <div className="space-y-5" data-testid="ai-assistant-page">
            <div className="flex flex-wrap items-end justify-between gap-3">
                <div>
                    <div className="label-cap">AI</div>
                    <h1 className="font-display text-3xl font-bold tracking-tight flex items-center gap-2">
                        <Sparkles className="h-7 w-7 text-primary" /> RGE REGALGOA AI Assistant
                    </h1>
                    <p className="text-sm text-muted-foreground mt-1">Ask questions, get GST/HSN suggestions, auto-categorise expenses, and pull live business insights — powered by GPT.</p>
                </div>
            </div>

            <Tabs value={tab} onValueChange={setTab}>
                <TabsList data-testid="ai-tabs">
                    <TabsTrigger value="chat" data-testid="tab-chat"><Bot className="h-3.5 w-3.5 mr-1.5" /> Chat</TabsTrigger>
                    <TabsTrigger value="insights" data-testid="tab-insights"><TrendingUp className="h-3.5 w-3.5 mr-1.5" /> Insights</TabsTrigger>
                    <TabsTrigger value="gst" data-testid="tab-gst"><Tag className="h-3.5 w-3.5 mr-1.5" /> GST/HSN</TabsTrigger>
                    <TabsTrigger value="expense" data-testid="tab-expense"><Receipt className="h-3.5 w-3.5 mr-1.5" /> Expense Categorise</TabsTrigger>
                </TabsList>

                {/* CHAT */}
                <TabsContent value="chat" className="mt-4">
                    <Card>
                        <CardContent className="p-0">
                            <div ref={listRef} className="h-[440px] overflow-y-auto p-4 space-y-3 bg-muted/10" data-testid="ai-chat-list">
                                {messages.length === 0 ? (
                                    <div className="text-center py-8">
                                        <Sparkles className="h-10 w-10 text-primary/40 mx-auto mb-3" />
                                        <div className="text-sm font-medium">Hi! Main aapki business assistant hoon 👋</div>
                                        <div className="text-xs text-muted-foreground mt-1">Hindi ya English me kuch bhi puchhiye — ya neeche quick-prompts pe click karein.</div>
                                        <div className="flex flex-wrap gap-2 justify-center mt-5 max-w-lg mx-auto">
                                            {SUGGESTIONS.map((s) => (
                                                <button key={s.text} onClick={() => send(s.text)} className="text-xs px-3 py-1.5 rounded-full border bg-card hover:bg-primary/5 hover:border-primary transition-colors" data-testid={`suggestion-${s.text.slice(0, 10)}`}>
                                                    {s.icon} {s.text}
                                                </button>
                                            ))}
                                        </div>
                                    </div>
                                ) : messages.map((m, i) => (
                                    <Bubble key={i} role={m.role} text={m.text} error={m.error} />
                                ))}
                                {thinking && (
                                    <Bubble role="assistant" text="…" thinking />
                                )}
                            </div>
                            <div className="border-t p-3 flex items-center gap-2">
                                <Button
                                    size="icon"
                                    variant={recognizing ? "default" : "outline"}
                                    onClick={recognizing ? stopVoice : startVoice}
                                    title={recognizing ? "Stop listening" : "Start voice input"}
                                    className={recognizing ? "bg-rose-500 hover:bg-rose-600 animate-pulse" : ""}
                                    data-testid="ai-voice-btn"
                                >
                                    {recognizing ? <MicOff className="h-4 w-4" /> : <Mic className="h-4 w-4" />}
                                </Button>
                                <Input
                                    value={input}
                                    onChange={(e) => setInput(e.target.value)}
                                    onKeyDown={(e) => { if (e.key === "Enter") send(input); }}
                                    placeholder={recognizing ? "🎤 Listening…" : "Type or speak your question…"}
                                    disabled={recognizing || thinking}
                                    autoFocus
                                    data-testid="ai-input"
                                />
                                <Button onClick={() => send(input)} disabled={!input.trim() || thinking} className="bg-primary hover:bg-primary/90" data-testid="ai-send-btn">
                                    <Send className="h-4 w-4" />
                                </Button>
                            </div>
                        </CardContent>
                    </Card>
                </TabsContent>

                {/* INSIGHTS */}
                <TabsContent value="insights" className="mt-4 space-y-3">
                    <Card>
                        <CardContent className="p-5">
                            <div className="flex items-center justify-between mb-4">
                                <div>
                                    <h3 className="font-display text-base font-bold flex items-center gap-1.5"><TrendingUp className="h-4 w-4 text-primary" /> AI Business Health Report</h3>
                                    <p className="text-xs text-muted-foreground">Live snapshot + AI analysis · refreshes on demand</p>
                                </div>
                                <Button onClick={loadInsights} disabled={insightsLoading} className="bg-primary hover:bg-primary/90" data-testid="generate-insights-btn">
                                    <RefreshCw className={`h-4 w-4 mr-1.5 ${insightsLoading ? "animate-spin" : ""}`} /> {insights ? "Regenerate" : "Generate Now"}
                                </Button>
                            </div>
                            {insights ? (
                                <div className="prose prose-sm max-w-none dark:prose-invert" data-testid="insights-md">
                                    <ReactMarkdown>{insights.insights}</ReactMarkdown>
                                </div>
                            ) : (
                                <div className="text-center py-12 text-muted-foreground text-sm">
                                    Click <strong>Generate Now</strong> for your live business health report.
                                </div>
                            )}
                        </CardContent>
                    </Card>
                </TabsContent>

                {/* GST */}
                <TabsContent value="gst" className="mt-4">
                    <Card>
                        <CardContent className="p-5 space-y-4">
                            <h3 className="font-display text-base font-bold flex items-center gap-1.5"><Tag className="h-4 w-4 text-primary" /> AI HSN + GST Rate Suggestion</h3>
                            <p className="text-xs text-muted-foreground">Describe an item or service. AI suggests the HSN code and GST rate.</p>
                            <div className="flex gap-2">
                                <Input value={gstQuery} onChange={(e) => setGstQuery(e.target.value)} placeholder="e.g. brass ball valve 40mm, mobile phone accessories, software service" onKeyDown={(e) => e.key === "Enter" && suggestGst()} data-testid="gst-query" />
                                <Button onClick={suggestGst} disabled={gstLoading || !gstQuery.trim()} className="bg-primary hover:bg-primary/90" data-testid="gst-suggest-btn">
                                    {gstLoading ? <RefreshCw className="h-4 w-4 animate-spin" /> : "Suggest"}
                                </Button>
                            </div>
                            {gstResult && (
                                <div className="rounded-lg border border-primary/30 bg-primary/5 p-4" data-testid="gst-result">
                                    <div className="grid grid-cols-2 gap-3">
                                        <div>
                                            <div className="label-cap">HSN Code</div>
                                            <div className="font-mono text-2xl font-bold mt-1">{gstResult.hsn_code || "—"}</div>
                                        </div>
                                        <div>
                                            <div className="label-cap">GST Rate</div>
                                            <div className="num text-2xl font-bold mt-1 text-primary">{gstResult.gst_rate || 0}%</div>
                                        </div>
                                    </div>
                                    <p className="text-xs text-muted-foreground mt-3 italic">{gstResult.reasoning}</p>
                                </div>
                            )}
                        </CardContent>
                    </Card>
                </TabsContent>

                {/* EXPENSE */}
                <TabsContent value="expense" className="mt-4">
                    <Card>
                        <CardContent className="p-5 space-y-4">
                            <h3 className="font-display text-base font-bold flex items-center gap-1.5"><Receipt className="h-4 w-4 text-primary" /> AI Expense Categoriser</h3>
                            <p className="text-xs text-muted-foreground">Paste an expense description. AI picks the right accounting category.</p>
                            <div className="flex gap-2 flex-wrap">
                                <Input value={expQuery} onChange={(e) => setExpQuery(e.target.value)} placeholder="e.g. JIO recharge for office wifi" className="flex-1 min-w-[240px]" data-testid="exp-query" />
                                <Input type="number" value={expAmount} onChange={(e) => setExpAmount(e.target.value)} placeholder="Amount" className="w-32" data-testid="exp-amount" />
                                <Button onClick={categorize} disabled={expLoading || !expQuery.trim()} className="bg-primary hover:bg-primary/90" data-testid="exp-categorize-btn">
                                    {expLoading ? <RefreshCw className="h-4 w-4 animate-spin" /> : "Categorise"}
                                </Button>
                            </div>
                            {expResult && (
                                <div className="rounded-lg border border-primary/30 bg-primary/5 p-4" data-testid="exp-result">
                                    <Badge className="text-sm">{expResult.category}</Badge>
                                    <p className="text-xs text-muted-foreground mt-2 italic">{expResult.reasoning}</p>
                                </div>
                            )}
                        </CardContent>
                    </Card>
                </TabsContent>
            </Tabs>
        </div>
    );
}

function Bubble({ role, text, thinking, error }) {
    const isUser = role === "user";
    return (
        <div className={`flex gap-2 ${isUser ? "justify-end" : "justify-start"}`}>
            {!isUser && (
                <div className="h-7 w-7 rounded-full bg-primary text-primary-foreground flex items-center justify-center flex-shrink-0">
                    <Sparkles className="h-3.5 w-3.5" />
                </div>
            )}
            <div className={`max-w-[78%] rounded-2xl px-3.5 py-2 ${isUser ? "bg-primary text-primary-foreground" : error ? "bg-rose-50 text-rose-900 dark:bg-rose-950/30 dark:text-rose-200" : "bg-card border border-border"}`}>
                {thinking ? (
                    <div className="flex gap-1 py-1">
                        <span className="h-1.5 w-1.5 bg-muted-foreground rounded-full animate-bounce" />
                        <span className="h-1.5 w-1.5 bg-muted-foreground rounded-full animate-bounce" style={{ animationDelay: "0.15s" }} />
                        <span className="h-1.5 w-1.5 bg-muted-foreground rounded-full animate-bounce" style={{ animationDelay: "0.3s" }} />
                    </div>
                ) : isUser ? (
                    <p className="text-sm whitespace-pre-wrap">{text}</p>
                ) : (
                    <div className="prose prose-sm dark:prose-invert max-w-none text-sm">
                        <ReactMarkdown>{text}</ReactMarkdown>
                    </div>
                )}
            </div>
            {isUser && (
                <div className="h-7 w-7 rounded-full bg-muted flex items-center justify-center flex-shrink-0">
                    <UserIcon className="h-3.5 w-3.5" />
                </div>
            )}
        </div>
    );
}
