import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { useState } from "react";
import { toast } from "sonner";
import {
  Loader2, Plus, Store, DollarSign, ShoppingBag, Package, MessageSquare, RotateCcw, AlertTriangle,
  LineChart as LineChartIcon, Layers, Bell, CreditCard, User2, Activity as ActivityIcon,
} from "lucide-react";

import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle,
} from "@/components/ui/dialog";
import { getMe } from "@/lib/dashboard.functions";


export const Route = createFileRoute("/_authenticated/dashboard")({
  head: () => ({ meta: [{ title: "Dashboard — eBay BOS" }] }),
  component: Dashboard,
});

function Dashboard() {
  const fetchMe = useServerFn(getMe);
  const me = useQuery({ queryKey: ["me"], queryFn: () => fetchMe({ data: undefined as never }) });

  const [upgradeOpen, setUpgradeOpen] = useState(false);

  async function handleConnect() {
    // Phase 1.5: Button routes to the future connection flow. No OAuth/API calls.
    setUpgradeOpen(true);
  }


  if (me.isLoading) {
    return <div className="flex min-h-[50vh] items-center justify-center"><Loader2 className="h-5 w-5 animate-spin text-muted-foreground" /></div>;
  }
  if (!me.data) return null;

  const displayName = me.data.profile.full_name ?? me.data.email ?? "there";


  return (
    <div className="mx-auto max-w-7xl space-y-6 px-6 py-8">
      {/* Header */}
      <header className="flex flex-wrap items-start justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Welcome back, {displayName}</h1>
          <p className="mt-1 flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
            <span>Workspace: <strong className="text-foreground">{me.data.workspace?.name ?? "—"}</strong></span>
            <span className="text-muted-foreground/50">·</span>
            <Badge variant={me.data.plan?.code === "premium" ? "default" : "secondary"} className="gap-1">
              <CreditCard className="h-3 w-3" /> {me.data.plan?.name ?? "Free Forever"}
            </Badge>
          </p>
        </div>
        <Button onClick={handleConnect} size="lg" className="shadow-sm">
          <Plus className="mr-2 h-4 w-4" />
          Connect eBay Account
        </Button>

      </header>

      {/* KPI cards */}
      <section className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        <Kpi icon={<DollarSign className="h-4 w-4" />} label="Sales" value={null} />
        <Kpi icon={<ShoppingBag className="h-4 w-4" />} label="Orders" value={null} />
        <Kpi icon={<LineChartIcon className="h-4 w-4" />} label="Revenue" value={null} />
        <Kpi icon={<Package className="h-4 w-4" />} label="Listings" value={null} />
        <Kpi icon={<MessageSquare className="h-4 w-4" />} label="Messages" value={null} />
        <Kpi icon={<RotateCcw className="h-4 w-4" />} label="Returns" value={null} />
        <Kpi icon={<Store className="h-4 w-4" />} label="Connected Accounts" value={null} highlight />
        <Kpi icon={<AlertTriangle className="h-4 w-4" />} label="Inventory Alerts" value={null} />

      </section>

      {/* Sales chart */}
      <section className="rounded-xl border bg-card p-6">
        <div className="mb-4 flex items-center justify-between">
          <div>
            <h2 className="text-sm font-semibold">Today's Sales</h2>
            <p className="text-xs text-muted-foreground">Hourly revenue and order count</p>
          </div>
        </div>
        <div className="flex h-64 flex-col items-center justify-center rounded-lg border border-dashed text-center">
          <LineChartIcon className="h-8 w-8 text-muted-foreground" />
          <p className="mt-3 text-sm font-medium">Sales graphs will load in Phase 2</p>
          <p className="mt-1 max-w-xs text-xs text-muted-foreground">
            The dashboard graph container is ready, but production charts require live eBay data.
          </p>
        </div>

      </section>

      {/* Quick actions */}
      <section>
        <h2 className="mb-3 text-sm font-semibold">Quick actions</h2>
        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
          <ActionCard icon={<Plus className="h-4 w-4" />} title="Connect eBay Account" body="Add another eBay store." onClick={handleConnect} />
          <ActionCard icon={<Layers className="h-4 w-4" />} title="Manage Workspaces" body="Create and switch workspaces." to="/workspaces" />
          <ActionCard icon={<Bell className="h-4 w-4" />} title="Notifications" body="View recent alerts and messages." to="/notifications" />
          <ActionCard icon={<CreditCard className="h-4 w-4" />} title="Subscription" body="See your plan and upgrade options." to="/subscription" />
          <ActionCard icon={<User2 className="h-4 w-4" />} title="Profile settings" body="Update your name and preferences." to="/settings" />
          <ActionCard icon={<ActivityIcon className="h-4 w-4" />} title="Recent activity" body="See what happened recently." to="/notifications" />
        </div>
      </section>

      {/* Upgrade dialog */}
      <Dialog open={upgradeOpen} onOpenChange={setUpgradeOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>You've reached your account limit</DialogTitle>
            <DialogDescription>
              The <strong>Free Forever</strong> plan allows one connected eBay account. Upgrade to{" "}
              <strong>Premium</strong> to connect unlimited eBay accounts and unlock all features.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setUpgradeOpen(false)}>Cancel</Button>
            <Button asChild>
              <Link to="/subscription">Upgrade to Premium</Link>
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

function Kpi({ icon, label, value, highlight }: { icon: React.ReactNode; label: string; value: React.ReactNode; highlight?: boolean }) {
  return (
    <div className={`rounded-xl border bg-card p-4 ${highlight ? "ring-1 ring-primary/30" : ""}`}>
      <div className="flex items-center gap-2 text-xs text-muted-foreground">{icon} {label}</div>
      <div className="mt-2 text-2xl font-bold">
        {value ?? <span className="text-lg font-medium text-muted-foreground">—</span>}
      </div>
    </div>
  );
}

function ActionCard({
  icon, title, body, to, onClick,
}: {
  icon: React.ReactNode; title: string; body: string;
  to?: "/workspaces" | "/notifications" | "/subscription" | "/settings";
  onClick?: () => void;
}) {
  const inner = (
    <div className="group flex h-full items-start gap-3 rounded-xl border bg-card p-4 text-left transition-colors hover:bg-accent">
      <div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-primary/10 text-primary">{icon}</div>
      <div className="min-w-0">
        <div className="font-medium">{title}</div>
        <div className="mt-0.5 text-xs text-muted-foreground">{body}</div>
      </div>
    </div>
  );
  if (to) return <Link to={to}>{inner}</Link>;
  return <button type="button" onClick={onClick} className="text-left">{inner}</button>;
}


