"use client";

import { useState, useCallback } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  TrendingUp,
  TrendingDown,
  DollarSign,
  Briefcase,
  Trophy,
  AlertCircle,
  Plus,
  RefreshCw,
  Activity,
  Zap,
} from "lucide-react";

import CircuitBackground from "./components/CircuitBackground";
import DropZone from "./components/DropZone";
import StatCard from "./components/StatCard";
import StockTable from "./components/StockTable";
import PortfolioChart from "./components/PortfolioChart";
import ErrorBanner from "./components/ErrorBanner";

import { StockEntry } from "@/lib/types";
import {
  enrichWithCurrentPrice,
  calculatePortfolioStats,
  buildChartData,
  formatCurrency,
  formatPercent,
} from "@/lib/portfolio";

type AppState = "idle" | "analyzing" | "dashboard" | "error";

export default function Home() {
  const [appState, setAppState] = useState<AppState>("idle");
  const [stocks, setStocks] = useState<StockEntry[]>([]);
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);
  const [errorMessage, setErrorMessage] = useState<string>("");
  const [isAddingMore, setIsAddingMore] = useState(false);

  const stats = calculatePortfolioStats(stocks);
  const chartData = buildChartData(stocks);

  const analyzeImage = useCallback(async (file: File) => {
    setAppState("analyzing");
    setErrorMessage("");
    const formData = new FormData();
    formData.append("image", file);

    try {
      const res = await fetch("/api/analyze-portfolio", { method: "POST", body: formData });
      const json = await res.json();

      if (!res.ok || !json.success) {
        setErrorMessage(json.error ?? "Analysis failed. Please try again.");
        setAppState(stocks.length > 0 ? "dashboard" : "error");
        return;
      }

      const enriched = enrichWithCurrentPrice(json.data as StockEntry[]);

      if (isAddingMore) {
        setStocks((prev) => {
          const existing = new Map(prev.map((s) => [s.stock_name.toLowerCase(), s]));
          enriched.forEach((s) => {
            if (!existing.has(s.stock_name.toLowerCase())) existing.set(s.stock_name.toLowerCase(), s);
          });
          return Array.from(existing.values());
        });
      } else {
        setStocks(enriched);
      }

      setAppState("dashboard");
      setIsAddingMore(false);
    } catch {
      setErrorMessage("Network error. Please check your connection and try again.");
      setAppState(stocks.length > 0 ? "dashboard" : "error");
    }
  }, [isAddingMore, stocks.length]);

  const handleImageSelected = useCallback((file: File) => {
    const url = URL.createObjectURL(file);
    setPreviewUrl(url);
    analyzeImage(file);
  }, [analyzeImage]);

  const handleClear = useCallback(() => {
    if (previewUrl) URL.revokeObjectURL(previewUrl);
    setPreviewUrl(null);
    if (!isAddingMore) setAppState(stocks.length > 0 ? "dashboard" : "idle");
  }, [previewUrl, isAddingMore, stocks.length]);

  const handleReset = useCallback(() => {
    if (previewUrl) URL.revokeObjectURL(previewUrl);
    setPreviewUrl(null);
    setStocks([]);
    setAppState("idle");
    setErrorMessage("");
    setIsAddingMore(false);
  }, [previewUrl]);

  const handleAddMore = useCallback(() => {
    setIsAddingMore(true);
    if (previewUrl) URL.revokeObjectURL(previewUrl);
    setPreviewUrl(null);
    setAppState("idle");
  }, [previewUrl]);

  const isOverallProfit = stats.totalPnL >= 0;
  const pnlVariant = stats.totalPnL === 0 ? "neutral" : isOverallProfit ? "profit" : "loss";

  return (
    <main className="relative min-h-dvh z-10">
      <CircuitBackground />

      {/* ── Header ── */}
      <header className="relative z-10 px-6 pt-8 pb-6 flex items-center justify-between max-w-screen-xl mx-auto">
        <motion.div
          initial={{ opacity: 0, x: -20 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ duration: 0.6, ease: [0.22, 1, 0.36, 1] }}
          className="flex items-center gap-3"
        >
          <div
            className="w-10 h-10 rounded-phi flex items-center justify-center"
            style={{
              background: "linear-gradient(135deg, rgba(29,111,235,0.3), rgba(74,144,245,0.15))",
              border: "1px solid rgba(29, 111, 235, 0.4)",
              boxShadow: "0 0 20px rgba(29, 111, 235, 0.2)",
            }}
          >
            <Activity size={18} style={{ color: "#4A90F5" }} />
          </div>
          <div>
            <h1 className="font-display font-bold text-phi-xl leading-none gradient-text">NEXUS</h1>
            <p className="text-phi-xs font-data tracking-widest" style={{ color: "#7A9ABF" }}>AI PORTFOLIO INTELLIGENCE</p>
          </div>
        </motion.div>

        <motion.div
          initial={{ opacity: 0, x: 20 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ duration: 0.6, ease: [0.22, 1, 0.36, 1] }}
          className="flex items-center gap-2"
        >
          <div
            className="flex items-center gap-2 px-3 py-1.5 rounded-full text-phi-xs font-data"
            style={{ background: "rgba(29, 111, 235, 0.1)", border: "1px solid rgba(29, 111, 235, 0.2)", color: "#4A90F5" }}
          >
            <Zap size={10} />
            <span>Groq · Llama-4-Scout</span>
          </div>

          {stocks.length > 0 && (
            <motion.button
              initial={{ opacity: 0, scale: 0.8 }} animate={{ opacity: 1, scale: 1 }}
              whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}
              onClick={handleReset}
              className="flex items-center gap-1.5 px-3 py-1.5 rounded-full text-phi-xs font-data transition-colors"
              style={{ background: "rgba(240, 62, 62, 0.08)", border: "1px solid rgba(240, 62, 62, 0.2)", color: "#F03E3E" }}
            >
              <RefreshCw size={10} />
              <span>Reset</span>
            </motion.button>
          )}
        </motion.div>
      </header>

      <div className="relative z-10 max-w-screen-xl mx-auto px-6 pb-16">

        {/* ── Error Banner ── */}
        <AnimatePresence>
          {errorMessage && <ErrorBanner message={errorMessage} onDismiss={() => setErrorMessage("")} />}
        </AnimatePresence>

        <AnimatePresence mode="wait">

          {/* ── IDLE / UPLOAD STATE ── */}
          {(appState === "idle" || appState === "analyzing") && (
            <motion.section
              key="upload"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              transition={{ duration: 0.5, ease: [0.22, 1, 0.36, 1] }}
              className="flex flex-col items-center justify-center min-h-[80vh] gap-8"
            >
              {/* Hero Text */}
              <motion.div
                initial={{ opacity: 0, y: 30 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.7, delay: 0.1, ease: [0.22, 1, 0.36, 1] }}
                className="text-center"
              >
                <h2 className="font-display font-bold text-phi-3xl gradient-text leading-tight">
                  {isAddingMore ? "Add More Holdings" : "Upload Your Portfolio"}
                </h2>
                <p className="text-phi-base mt-3 max-w-lg mx-auto" style={{ color: "#7A9ABF" }}>
                  {isAddingMore
                    ? "Drop another screenshot to merge more stocks into your portfolio."
                    : "Drop a screenshot of your stock platform. Groq's Llama-4-Scout Vision will extract all holdings instantly."}
                </p>
              </motion.div>

              {/* Drop Zone */}
              <motion.div
                initial={{ opacity: 0, scale: 0.95 }}
                animate={{ opacity: 1, scale: 1 }}
                transition={{ duration: 0.6, delay: 0.2, ease: [0.22, 1, 0.36, 1] }}
                className="w-full max-w-2xl"
              >
                <DropZone
                  onImageSelected={handleImageSelected}
                  isAnalyzing={appState === "analyzing"}
                  previewUrl={previewUrl}
                  onClear={handleClear}
                />
              </motion.div>

              {/* Feature Pills */}
              {!isAddingMore && (
                <motion.div
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  transition={{ delay: 0.5 }}
                  className="flex flex-wrap gap-3 justify-center"
                >
                  {[
                    "📊 Auto P&L Calculation",
                    "🔍 AI Vision Extraction",
                    "📈 Portfolio Analytics",
                    "⚡ Groq Ultra-Fast",
                  ].map((feat) => (
                    <span
                      key={feat}
                      className="px-4 py-2 rounded-full text-phi-xs font-data"
                      style={{ background: "rgba(17, 38, 84, 0.6)", border: "1px solid rgba(29, 111, 235, 0.18)", color: "#A8C8F0" }}
                    >
                      {feat}
                    </span>
                  ))}
                </motion.div>
              )}

              {isAddingMore && (
                <button
                  onClick={() => { setIsAddingMore(false); setAppState("dashboard"); }}
                  className="text-phi-sm font-data underline underline-offset-4 transition-colors"
                  style={{ color: "#7A9ABF" }}
                >
                  Cancel — go back to dashboard
                </button>
              )}
            </motion.section>
          )}

          {/* ── DASHBOARD STATE ── */}
          {appState === "dashboard" && stocks.length > 0 && (
            <motion.section
              key="dashboard"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.4 }}
            >
              {/* Section header */}
              <div className="flex items-center justify-between mb-6">
                <div>
                  <h2 className="font-display font-bold text-phi-2xl gradient-text">Portfolio Overview</h2>
                  <p className="text-phi-sm font-data mt-0.5" style={{ color: "#7A9ABF" }}>
                    {stocks.length} holding{stocks.length !== 1 ? "s" : ""} · Simulated live prices
                  </p>
                </div>
                <motion.button
                  whileHover={{ scale: 1.04 }} whileTap={{ scale: 0.96 }}
                  onClick={handleAddMore}
                  className="flex items-center gap-2 px-4 py-2 rounded-phi text-phi-sm font-display font-semibold transition-all"
                  style={{
                    background: "rgba(29, 111, 235, 0.15)",
                    border: "1px solid rgba(29, 111, 235, 0.35)",
                    color: "#4A90F5",
                  }}
                >
                  <Plus size={14} />
                  Add More
                </motion.button>
              </div>

              {/* Stat Cards */}
              <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
                <StatCard
                  label="Total Invested"
                  value={formatCurrency(stats.totalInvestment, true)}
                  subValue={`${stats.stockCount} stocks`}
                  icon={Briefcase}
                  variant="azure"
                  delay={0}
                />
                <StatCard
                  label="Current Value"
                  value={formatCurrency(stats.totalCurrentValue, true)}
                  icon={DollarSign}
                  variant="neutral"
                  delay={0.07}
                />
                <StatCard
                  label="Total P&L"
                  value={(stats.totalPnL >= 0 ? "+" : "") + formatCurrency(stats.totalPnL, true)}
                  subValue={formatPercent(stats.totalPnLPercent)}
                  icon={stats.totalPnL >= 0 ? TrendingUp : TrendingDown}
                  variant={pnlVariant}
                  delay={0.14}
                />
                <StatCard
                  label="Best Performer"
                  value={stats.bestPerformer?.stock_name ?? "—"}
                  subValue={
                    stats.bestPerformer
                      ? formatPercent(
                          ((((stats.bestPerformer.current_price ?? stats.bestPerformer.buy_price) - stats.bestPerformer.buy_price) / stats.bestPerformer.buy_price) * 100)
                        )
                      : undefined
                  }
                  icon={Trophy}
                  variant="profit"
                  delay={0.21}
                />
              </div>

              {/* Golden ratio 2-col layout: 61.8% left, 38.2% right */}
              <div className="grid grid-cols-1 xl:grid-cols-[61.8fr_38.2fr] gap-6">

                {/* LEFT — Holdings Table */}
                <div className="flex flex-col gap-6">
                  <motion.div
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.5, delay: 0.25, ease: [0.22, 1, 0.36, 1] }}
                    className="rounded-phi-lg p-6"
                    style={{
                      background: "rgba(17, 38, 84, 0.6)",
                      border: "1px solid rgba(29, 111, 235, 0.15)",
                      backdropFilter: "blur(14px)",
                      boxShadow: "0 8px 32px rgba(0,0,0,0.35)",
                    }}
                  >
                    <div className="flex items-center justify-between mb-5">
                      <h3 className="font-display font-semibold text-phi-base" style={{ color: "#EEF5FF" }}>Holdings</h3>
                      <div className="flex items-center gap-2 text-phi-xs font-data" style={{ color: "rgba(29, 111, 235, 0.7)" }}>
                        <div className="w-1.5 h-1.5 rounded-full animate-pulse" style={{ background: "#1D6FEB" }} />
                        Live P&L
                      </div>
                    </div>
                    <StockTable stocks={stocks} />
                  </motion.div>
                </div>

                {/* RIGHT — Chart + Allocation */}
                <div className="flex flex-col gap-6">
                  <motion.div
                    initial={{ opacity: 0, x: 20 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ duration: 0.5, delay: 0.2, ease: [0.22, 1, 0.36, 1] }}
                    className="rounded-phi-lg p-6"
                    style={{
                      background: "rgba(17, 38, 84, 0.6)",
                      border: "1px solid rgba(29, 111, 235, 0.15)",
                      backdropFilter: "blur(14px)",
                      boxShadow: "0 8px 32px rgba(0,0,0,0.35)",
                    }}
                  >
                    <PortfolioChart data={chartData} />
                  </motion.div>

                  {/* Allocation bars */}
                  <motion.div
                    initial={{ opacity: 0, x: 20 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ duration: 0.5, delay: 0.3, ease: [0.22, 1, 0.36, 1] }}
                    className="rounded-phi-lg p-6"
                    style={{
                      background: "rgba(17, 38, 84, 0.6)",
                      border: "1px solid rgba(29, 111, 235, 0.15)",
                      backdropFilter: "blur(14px)",
                      boxShadow: "0 8px 32px rgba(0,0,0,0.35)",
                    }}
                  >
                    <h3 className="font-display font-semibold text-phi-base mb-4" style={{ color: "#EEF5FF" }}>Allocation</h3>
                    <div className="flex flex-col gap-2">
                      {stocks.map((stock, idx) => {
                        const invested = stock.buy_price * stock.quantity;
                        const alloc = stats.totalInvestment > 0 ? (invested / stats.totalInvestment) * 100 : 0;
                        const current = (stock.current_price ?? stock.buy_price) * stock.quantity;
                        const isProfit = current >= invested;
                        return (
                          <motion.div
                            key={stock.id ?? idx}
                            initial={{ opacity: 0, x: 10 }}
                            animate={{ opacity: 1, x: 0 }}
                            transition={{ delay: 0.35 + idx * 0.05, duration: 0.3 }}
                            className="flex flex-col gap-1"
                          >
                            <div className="flex items-center justify-between text-phi-xs">
                              <span className="font-display font-medium" style={{ color: "#C8D8F0" }}>{stock.stock_name}</span>
                              <span className="font-data" style={{ color: "#7A9ABF" }}>{alloc.toFixed(1)}%</span>
                            </div>
                            <div className="h-1.5 rounded-full overflow-hidden" style={{ background: "rgba(29, 111, 235, 0.1)" }}>
                              <motion.div
                                initial={{ width: "0%" }}
                                animate={{ width: `${alloc}%` }}
                                transition={{ delay: 0.4 + idx * 0.05, duration: 0.7, ease: [0.22, 1, 0.36, 1] }}
                                className="h-full rounded-full"
                                style={{
                                  background: isProfit
                                    ? "linear-gradient(90deg, rgba(0,200,117,0.6), rgba(0,200,117,0.9))"
                                    : "linear-gradient(90deg, rgba(240,62,62,0.6), rgba(240,62,62,0.9))",
                                }}
                              />
                            </div>
                          </motion.div>
                        );
                      })}
                    </div>
                  </motion.div>

                  {/* Worst performer warning */}
                  {stats.worstPerformer && stats.totalPnL < 0 && (
                    <motion.div
                      initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: 0.5 }}
                      className="rounded-phi p-4 flex gap-3"
                      style={{ background: "rgba(240, 62, 62, 0.06)", border: "1px solid rgba(240, 62, 62, 0.2)" }}
                    >
                      <AlertCircle size={16} style={{ color: "#F03E3E", flexShrink: 0 }} />
                      <div>
                        <p className="text-phi-xs font-display font-semibold" style={{ color: "#F03E3E" }}>Weakest Position</p>
                        <p className="text-phi-xs font-data mt-1" style={{ color: "#7A9ABF" }}>
                          {stats.worstPerformer.stock_name} is dragging returns. Consider reviewing your position.
                        </p>
                      </div>
                    </motion.div>
                  )}

                  <p className="text-phi-xs text-center font-data" style={{ color: "rgba(122,154,191,0.5)" }}>
                    Current prices are simulated for demo purposes.<br />
                    Connect a market data API for live quotes.
                  </p>
                </div>
              </div>
            </motion.section>
          )}

          {/* ── ERROR STATE ── */}
          {appState === "error" && (
            <motion.section
              key="error"
              initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
              className="flex flex-col items-center justify-center min-h-[60vh] gap-6 text-center"
            >
              <div className="w-20 h-20 rounded-full flex items-center justify-center"
                style={{ background: "rgba(240, 62, 62, 0.1)", border: "1px solid rgba(240,62,62,0.3)" }}>
                <AlertCircle size={36} style={{ color: "#F03E3E" }} />
              </div>
              <div>
                <h2 className="font-display font-bold text-phi-2xl" style={{ color: "#EEF5FF" }}>Analysis Failed</h2>
                <p className="text-phi-base mt-2 max-w-md" style={{ color: "#7A9ABF" }}>
                  {errorMessage || "Something went wrong. Please try again with a different screenshot."}
                </p>
              </div>
              <button
                onClick={handleReset}
                className="flex items-center gap-2 px-6 py-3 rounded-phi font-display font-semibold text-phi-sm transition-all hover:opacity-90"
                style={{
                  background: "linear-gradient(135deg, rgba(29,111,235,0.8), rgba(29,111,235,0.5))",
                  border: "1px solid rgba(29, 111, 235, 0.4)",
                  color: "#EEF5FF",
                }}
              >
                <RefreshCw size={14} />
                Try Again
              </button>
            </motion.section>
          )}

        </AnimatePresence>
      </div>
    </main>
  );
}
