import {notFound, redirect} from "next/navigation";
import {auth} from "@/auth";
import {prisma} from "@/lib/db/prisma";
import {getTenantDb} from "@/lib/db/tenant";
import {Button} from "@/components/ui/button";
import {Card, CardContent, CardHeader, CardTitle} from "@/components/ui/card";
import {Input} from "@/components/ui/input";
import {Label} from "@/components/ui/label";
import {Plus, GitBranch} from "lucide-react";
import {createBranch} from "@/features/branches/server/actions";
import {BranchToggle} from "./branch-toggle";

export default async function BranchesPage({params}: {params: Promise<{tenantSlug: string; locale: string}>}) {
  const {tenantSlug, locale} = await params;
  const session = await auth();
  if (!session?.user?.id) redirect(`/${locale}/auth/sign-in`);

  const tenant = await prisma.tenant.findUnique({where: {slug: tenantSlug}});
  if (!tenant) notFound();

  const db = getTenantDb(tenant.id);
  const branches = await db.branch.findMany({orderBy: {name: "asc"}});

  async function handleCreate(formData: FormData) {
    "use server";
    formData.set("tenantSlug", tenantSlug);
    await createBranch(formData);
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Branches</h1>
          <p className="mt-1 text-slate-500">{branches.length} branch{branches.length !== 1 ? "es" : ""}</p>
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Plus className="h-4 w-4" />
            Add New Branch
          </CardTitle>
        </CardHeader>
        <CardContent>
          <form action={handleCreate} className="grid gap-4 sm:grid-cols-2">
            <div>
              <Label htmlFor="name">Branch Name *</Label>
              <Input id="name" name="name" className="mt-1" required />
            </div>
            <div>
              <Label htmlFor="code">Branch Code</Label>
              <Input id="code" name="code" className="mt-1" placeholder="e.g. BR-01" />
            </div>
            <div>
              <Label htmlFor="city">City</Label>
              <Input id="city" name="city" className="mt-1" />
            </div>
            <div>
              <Label htmlFor="country">Country</Label>
              <Input id="country" name="country" className="mt-1" />
            </div>
            <div>
              <Label htmlFor="phone">Phone</Label>
              <Input id="phone" name="phone" className="mt-1" />
            </div>
            <div>
              <Label htmlFor="email">Email</Label>
              <Input id="email" name="email" type="email" className="mt-1" />
            </div>
            <div className="sm:col-span-2 flex justify-end">
              <Button type="submit" className="gap-2">
                <Plus className="h-4 w-4" />
                Create Branch
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>

      <div className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm overflow-x-auto">
        <table className="min-w-full text-sm">
          <thead>
            <tr className="border-b border-slate-200">
              <th className="px-3 py-3 text-left font-semibold">Branch Name</th>
              <th className="px-3 py-3 text-left font-semibold">City</th>
              <th className="px-3 py-3 text-left font-semibold">Phone</th>
              <th className="px-3 py-3 text-left font-semibold">Email</th>
              <th className="px-3 py-3 text-left font-semibold">Status</th>
              <th className="px-3 py-3 text-left font-semibold">Actions</th>
            </tr>
          </thead>
          <tbody>
            {branches.map((b) => (
              <tr key={b.id} className="border-b border-slate-100 hover:bg-slate-50">
                <td className="px-3 py-3">
                  <div className="flex items-center gap-2">
                    <GitBranch className="h-4 w-4 text-blue-600 shrink-0" />
                    <span className="font-medium">{b.name}</span>
                  </div>
                </td>
                <td className="px-3 py-3">{b.city || "—"}</td>
                <td className="px-3 py-3">{b.phone || "—"}</td>
                <td className="px-3 py-3">{b.email || "—"}</td>
                <td className="px-3 py-3">
                  <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${b.isActive ? "bg-green-100 text-green-700" : "bg-slate-100 text-slate-500"}`}>
                    {b.isActive ? "Active" : "Inactive"}
                  </span>
                </td>
                <td className="px-3 py-3">
                  <BranchToggle branchId={b.id} tenantSlug={tenantSlug} isActive={b.isActive} />
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
