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 {Tag, Plus} from "lucide-react";
import {createCoupon} from "@/features/coupons/server/actions";
import {CouponToggle} from "./coupon-toggle";

export default async function CouponsPage({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 coupons = await db.coupon.findMany({orderBy: {createdAt: "desc"}});

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

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-slate-900">Coupons</h1>
        <p className="mt-1 text-slate-500">{coupons.length} coupon{coupons.length !== 1 ? "s" : ""}</p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Plus className="h-4 w-4" />
            Create New Coupon
          </CardTitle>
        </CardHeader>
        <CardContent>
          <form action={handleCreate} className="grid gap-4 sm:grid-cols-2">
            <div>
              <Label htmlFor="code">Coupon Code *</Label>
              <Input id="code" name="code" className="mt-1 uppercase" placeholder="e.g. SUMMER20" required />
            </div>
            <div>
              <Label htmlFor="type">Discount Type *</Label>
              <select id="type" name="type" className="mt-1 w-full rounded-lg border border-slate-200 px-3 py-2" defaultValue="PERCENTAGE" required>
                <option value="PERCENTAGE">Percentage (%)</option>
                <option value="FIXED_AMOUNT">Fixed Amount ($)</option>
              </select>
            </div>
            <div>
              <Label htmlFor="value">Value *</Label>
              <Input id="value" name="value" type="number" step="0.01" min="0.01" className="mt-1" required />
            </div>
            <div>
              <Label htmlFor="usageLimit">Usage Limit</Label>
              <Input id="usageLimit" name="usageLimit" type="number" min="1" className="mt-1" placeholder="Unlimited" />
            </div>
            <div>
              <Label htmlFor="minimumAmount">Minimum Order Amount</Label>
              <Input id="minimumAmount" name="minimumAmount" type="number" step="0.01" min="0" className="mt-1" placeholder="No minimum" />
            </div>
            <div>
              <Label htmlFor="endsAt">Expiry Date</Label>
              <Input id="endsAt" name="endsAt" type="date" className="mt-1" />
            </div>
            <div className="sm:col-span-2 flex justify-end">
              <Button type="submit" className="gap-2">
                <Tag className="h-4 w-4" />
                Create Coupon
              </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">Code</th>
              <th className="px-3 py-3 text-left font-semibold">Type</th>
              <th className="px-3 py-3 text-left font-semibold">Value</th>
              <th className="px-3 py-3 text-left font-semibold">Usage</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>
            {coupons.map((c) => (
              <tr key={c.id} className="border-b border-slate-100 hover:bg-slate-50">
                <td className="px-3 py-3">
                  <span className="font-mono font-semibold bg-slate-100 px-2 py-0.5 rounded text-sm">{c.code}</span>
                </td>
                <td className="px-3 py-3">{c.type === "PERCENTAGE" ? "Percentage" : "Fixed Amount"}</td>
                <td className="px-3 py-3 font-semibold text-green-700">
                  {c.type === "PERCENTAGE" ? `${c.value}%` : `$${c.value}`}
                </td>
                <td className="px-3 py-3">
                  {c.usedCount} / {c.usageLimit ?? "∞"}
                </td>
                <td className="px-3 py-3">
                  <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${c.isActive ? "bg-green-100 text-green-700" : "bg-slate-100 text-slate-500"}`}>
                    {c.isActive ? "Active" : "Inactive"}
                  </span>
                </td>
                <td className="px-3 py-3">
                  <CouponToggle couponId={c.id} tenantSlug={tenantSlug} isActive={c.isActive} />
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
