"use client";

import { BASE_PATH } from "@/lib/config";
import { useState, useEffect } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import {
  Home,
  Users,
  List,
  BarChart3,
  FileText,
  Plus,
  X,
  Clock,
  LogOut,
  Timer,
  CalendarPlus,
  Receipt,
  UserPlus,
  Settings,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from "@/components/ui/sheet";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { cn } from "@/lib/utils";
import { TimerForm } from "./timer-form";
import { QuickEntryForm } from "./quick-entry-form";
import { NewClientForm } from "./new-client-form";
import type { SessionUser } from "@/lib/auth";

const nav = [
  { href: "/", icon: Home, label: "Home" },
  { href: "/entries", icon: List, label: "Entries" },
  { href: "/analytics", icon: BarChart3, label: "Analytics" },
  { href: "/invoices", icon: FileText, label: "Invoices" },
  { href: "/clients", icon: Users, label: "Clients" },
];

export function AppShell({ user, children }: { user: SessionUser; children: React.ReactNode }) {
  const pathname = usePathname();
  const router = useRouter();
  const [menuOpen, setMenuOpen] = useState(false);
  const [quickOpen, setQuickOpen] = useState(false);
  const [quickTab, setQuickTab] = useState<"timer" | "entry" | "invoice" | "client">("timer");

  async function logout() {
    await fetch(`${BASE_PATH}/api/auth/logout`, { method: "POST" });
    router.replace("/login");
  }

  return (
    <div className="flex min-h-screen flex-col bg-background pb-24 md:pb-0 md:pl-64">
      <aside className="hidden md:fixed md:inset-y-0 md:left-0 md:flex md:w-64 md:flex-col md:border-r md:bg-card">
        <div className="flex items-center gap-2 p-6">
          <div className="flex h-10 w-10 items-center justify-center rounded-full bg-accent">
            <Clock className="h-5 w-5 text-accent-foreground" />
          </div>
          <span className="text-xl font-semibold text-primary">TimeHustle</span>
        </div>
        <nav className="flex-1 space-y-1 px-4">
          {nav.map((item) => (
            <Link
              key={item.href}
              href={item.href}
              className={cn(
                "flex items-center gap-3 rounded-2xl px-4 py-3 text-sm font-medium transition-colors",
                pathname === item.href
                  ? "bg-accent text-accent-foreground"
                  : "text-muted-foreground hover:bg-muted hover:text-primary"
              )}
            >
              <item.icon className="h-5 w-5" />
              {item.label}
            </Link>
          ))}
        </nav>
        <div className="border-t p-4 space-y-1">
          <Link
            href="/settings"
            className={cn(
              "flex items-center gap-3 rounded-2xl px-4 py-3 text-sm font-medium transition-colors",
              pathname === "/settings"
                ? "bg-accent text-accent-foreground"
                : "text-muted-foreground hover:bg-muted hover:text-primary"
            )}
          >
            <Settings className="h-5 w-5" />
            Settings
          </Link>
          <button
            onClick={logout}
            className="flex w-full items-center gap-3 rounded-2xl px-4 py-3 text-sm font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-primary"
          >
            <LogOut className="h-5 w-5" />
            Sign out
          </button>
        </div>
      </aside>

      <header className="sticky top-0 z-10 flex items-center justify-between border-b bg-background/80 px-4 py-3 backdrop-blur md:hidden">
        <div className="flex items-center gap-2">
          <div className="flex h-8 w-8 items-center justify-center rounded-full bg-accent">
            <Clock className="h-4 w-4 text-accent-foreground" />
          </div>
          <span className="text-lg font-semibold text-primary">TimeHustle</span>
        </div>
        <Link href="/settings" className="rounded-full bg-secondary p-2 text-secondary-foreground">
          <Settings className="h-4 w-4" />
        </Link>
      </header>

      <main className="flex-1 p-4 md:p-8">{children}</main>

      <div className="fixed bottom-6 left-1/2 z-20 -translate-x-1/2 md:hidden">
        {menuOpen && (
          <div className="absolute bottom-16 left-1/2 -translate-x-1/2 space-y-3">
            {[
              { key: "timer", icon: Timer, label: "Start Timer", color: "bg-accent text-accent-foreground" },
              { key: "entry", icon: CalendarPlus, label: "Add Entry", color: "bg-secondary text-secondary-foreground" },
              { key: "invoice", icon: Receipt, label: "Create Invoice", color: "bg-primary text-primary-foreground" },
              { key: "client", icon: UserPlus, label: "Add Client", color: "bg-muted-foreground text-background" },
            ].map((action) => (
              <button
                key={action.key}
                onClick={() => {
                  setQuickTab(action.key as typeof quickTab);
                  setQuickOpen(true);
                  setMenuOpen(false);
                }}
                className={cn(
                  "flex w-max items-center gap-2 rounded-full px-4 py-2 text-sm font-medium shadow-lg transition-transform active:scale-95",
                  action.color
                )}
              >
                <action.icon className="h-4 w-4" />
                {action.label}
              </button>
            ))}
          </div>
        )}
        <button
          onClick={() => setMenuOpen(!menuOpen)}
          className={cn(
            "flex h-14 w-14 items-center justify-center rounded-full shadow-xl transition-all",
            menuOpen ? "rotate-45 bg-primary text-primary-foreground" : "bg-accent text-accent-foreground"
          )}
        >
          {menuOpen ? <X className="h-6 w-6" /> : <Plus className="h-6 w-6" />}
        </button>
      </div>

      <nav className="fixed bottom-0 left-0 right-0 z-10 border-t bg-background px-6 pb-6 pt-3 md:hidden">
        <div className="flex justify-between">
          {nav.map((item) => (
            <Link
              key={item.href}
              href={item.href}
              className={cn(
                "flex flex-col items-center gap-1 text-xs font-medium",
                pathname === item.href ? "text-primary" : "text-muted-foreground"
              )}
            >
              <item.icon className="h-5 w-5" />
              {item.label}
            </Link>
          ))}
        </div>
      </nav>

      <Dialog open={quickOpen} onOpenChange={setQuickOpen}>
        <DialogContent className="max-w-md rounded-3xl">
          <DialogHeader>
            <DialogTitle>
              {quickTab === "timer" && "Start Timer"}
              {quickTab === "entry" && "Add Time Entry"}
              {quickTab === "invoice" && "Create Invoice"}
              {quickTab === "client" && "Add Client"}
            </DialogTitle>
          </DialogHeader>
          {quickTab === "timer" && <TimerForm onClose={() => setQuickOpen(false)} />}
          {quickTab === "entry" && <QuickEntryForm onClose={() => setQuickOpen(false)} />}
          {quickTab === "invoice" && <InvoiceForm onClose={() => setQuickOpen(false)} />}
          {quickTab === "client" && <NewClientForm onClose={() => setQuickOpen(false)} />}
        </DialogContent>
      </Dialog>
    </div>
  );
}

// Lazy import to avoid circular deps
function InvoiceForm({ onClose }: { onClose: () => void }) {
  const router = useRouter();
  const [entries, setEntries] = useState<any[]>([]);
  const [clients, setClients] = useState<any[]>([]);
  const [selected, setSelected] = useState<string[]>([]);
  const [clientId, setClientId] = useState("");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetch(`${BASE_PATH}/api/entries`)
      .then((r) => r.json())
      .then((d) => setEntries((d.entries || []).filter((e: any) => e.status === "logged")));
    fetch(`${BASE_PATH}/api/clients`)
      .then((r) => r.json())
      .then((d) => setClients(d.clients || []));
  }, []);

  async function create() {
    if (!clientId || selected.length === 0) return;
    setLoading(true);
    const res = await fetch(`${BASE_PATH}/api/invoices`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ clientId, entryIds: selected }),
    });
    setLoading(false);
    if (res.ok) {
      onClose();
      router.push("/invoices");
    } else {
      alert("Failed to create invoice");
    }
  }

  return (
    <div className="space-y-4">
      <select
        className="w-full rounded-xl border p-3"
        value={clientId}
        onChange={(e) => setClientId(e.target.value)}
      >
        <option value="">Select client</option>
        {clients.map((c: any) => (
          <option key={c.id} value={c.id}>
            {c.name}
          </option>
        ))}
      </select>
      <div className="max-h-60 overflow-auto rounded-xl border">
        {entries.map((entry) => (
          <label key={entry.id} className="flex items-center gap-3 border-b p-3 last:border-0">
            <input
              type="checkbox"
              checked={selected.includes(entry.id)}
              onChange={(e) =>
                setSelected(e.target.checked ? [...selected, entry.id] : selected.filter((id) => id !== entry.id))
              }
            />
            <div className="flex-1 text-sm">
              <div className="font-medium">{entry.description || "Untitled"}</div>
              <div className="text-muted-foreground">{(entry.durationMinutes / 60).toFixed(2)} hrs @ ${entry.hourlyRate}</div>
            </div>
          </label>
        ))}
        {entries.length === 0 && <p className="p-4 text-sm text-muted-foreground">No unbilled entries.</p>}
      </div>
      <Button onClick={create} disabled={loading || !clientId || selected.length === 0} className="w-full rounded-full">
        {loading ? "Creating..." : "Create Invoice"}
      </Button>
    </div>
  );
}
