import { createFileRoute, Navigate, Link, useNavigate } from "@tanstack/react-router";
import { useAuth } from "@/contexts/AuthContext";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { LogOut, Camera, Search, FileText, Bell, Users, ShieldAlert, Clock } from "lucide-react";
import logo from "@/assets/tirs-logo.png";

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

function Dashboard() {
  const { isAuthenticated, loading, profile, roles, isLocalAdmin, signOut } = useAuth();
  const navigate = useNavigate();

  if (loading) return <div className="min-h-screen flex items-center justify-center">Loading…</div>;
  if (!isAuthenticated) return <Navigate to="/login" />;
  if (isLocalAdmin) return <Navigate to="/admin" />;

  const isPending = profile?.status === "pending";
  const isCommander = roles.includes("commander");

  return (
    <div className="min-h-screen bg-background">
      <header className="bg-gradient-hero text-primary-foreground shadow-elevated">
        <div className="max-w-6xl mx-auto px-4 py-3 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <img src={logo} alt="TIRS" width={1024} height={1024} loading="lazy" className="h-10 w-10 object-contain" />
            <div>
              <h1 className="font-bold leading-tight">TIRS</h1>
              <p className="text-xs opacity-80">{profile?.full_name} · {profile?.rank}</p>
            </div>
          </div>
          <Button size="sm" variant="ghost" onClick={async () => { await signOut(); navigate({ to: "/login" }); }} className="text-primary-foreground hover:bg-white/10">
            <LogOut className="h-4 w-4 mr-1" /> Sign out
          </Button>
        </div>
      </header>

      <main className="max-w-6xl mx-auto px-4 py-6 space-y-4">
        {isPending && (
          <Card className="border-warning bg-warning/10">
            <CardContent className="pt-6 flex items-start gap-3">
              <ShieldAlert className="h-5 w-5 text-warning shrink-0 mt-0.5" />
              <div>
                <h3 className="font-semibold">Account pending approval</h3>
                <p className="text-sm text-muted-foreground">
                  Your registration is awaiting administrator approval. Once approved you'll be able to upload tattoos, search the registry and create cases.
                </p>
              </div>
            </CardContent>
          </Card>
        )}

        <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
          <ActionCard icon={<Camera />} title="Upload Tattoo" desc="Capture & geo-tag a new tattoo" disabled={isPending} />
          <ActionCard icon={<Search />} title="Search Registry" desc="AI-powered tattoo matching" disabled={isPending} />
          <ActionCard icon={<FileText />} title="Cases" desc="Manage cases, IO and dockets" disabled={isPending} />
          <ActionCard icon={<Bell />} title="Notifications" desc="Recent activity & alerts" />
          {isCommander && <ActionCard icon={<Users />} title="Station Cases" desc="View station-wide case progress" />}
          {isCommander && <ActionCard icon={<Clock />} title="Retention Extensions" desc="Approve POPIA retention extensions" />}
        </div>

        <Card>
          <CardHeader>
            <CardTitle>Your Profile</CardTitle>
            <CardDescription>Active session</CardDescription>
          </CardHeader>
          <CardContent className="grid sm:grid-cols-2 gap-2 text-sm">
            <div><span className="text-muted-foreground">Email: </span>{profile?.email}</div>
            <div><span className="text-muted-foreground">Rank: </span>{profile?.rank}</div>
            <div className="flex items-center gap-2">
              <span className="text-muted-foreground">Status: </span>
              <Badge variant={profile?.status === "approved" ? "default" : "secondary"}>{profile?.status}</Badge>
            </div>
            <div className="flex items-center gap-2">
              <span className="text-muted-foreground">Roles: </span>
              {roles.map((r) => <Badge key={r} variant="outline">{r}</Badge>)}
            </div>
          </CardContent>
        </Card>
      </main>
    </div>
  );
}

function ActionCard({ icon, title, desc, disabled }: { icon: React.ReactNode; title: string; desc: string; disabled?: boolean }) {
  return (
    <Card className={disabled ? "opacity-50" : "hover:shadow-elevated transition-shadow cursor-pointer"}>
      <CardContent className="pt-6">
        <div className="h-10 w-10 rounded-lg bg-primary/10 text-primary flex items-center justify-center mb-3">
          {icon}
        </div>
        <h3 className="font-semibold">{title}</h3>
        <p className="text-sm text-muted-foreground">{desc}</p>
        {disabled && <p className="text-xs text-warning mt-2">Awaiting approval</p>}
      </CardContent>
    </Card>
  );
}
