"use client";

import { useCallback, useEffect, useState } from "react";
import { useParams } from "next/navigation";
import MainTitle from "@/components/layout/dashboard/main-title";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import DataService from "@/config/axios";
import { useRequireSuperAdmin } from "@/hooks/use-require-super-admin";
import { getApiErrorMessage } from "@/lib/api-error";
import { toast } from "sonner";

type CouponRow = {
  _id: string;
  code: string;
  type: string;
  value: number;
  applyTo?: "full_order" | "products_only";
  minOrder?: number;
  maxUses?: number;
  usedCount?: number;
  expiresAt?: string | null;
  active?: boolean;
  description?: string;
};

export default function ShopCouponsAdmin() {
  const ready = useRequireSuperAdmin();
  const params = useParams();
  const app = params.app as string;

  const [loading, setLoading] = useState(true);
  const [rows, setRows] = useState<CouponRow[]>([]);
  const [busy, setBusy] = useState(false);
  const [form, setForm] = useState({
    code: "",
    type: "percent",
    value: "10",
    applyTo: "full_order",
    minOrder: "0",
    maxUses: "0",
    description: "",
  });

  const load = useCallback(async () => {
    try {
      const res = await DataService.get("/admin/shop-coupons");
      setRows(res.data?.data || []);
    } catch (e: unknown) {
      toast.error(getApiErrorMessage(e, "Failed to load coupons"));
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (ready) load();
  }, [ready, load]);

  const create = async (e: React.FormEvent) => {
    e.preventDefault();
    setBusy(true);
    try {
      await DataService.post("/admin/shop-coupons", {
        code: form.code.trim(),
        type: form.type,
        value: Number(form.value),
        applyTo: form.applyTo,
        minOrder: Number(form.minOrder) || 0,
        maxUses: Number(form.maxUses) || 0,
        description: form.description.trim(),
        active: true,
      });
      toast.success("Coupon created");
      setForm({
        code: "",
        type: "percent",
        value: "10",
        applyTo: "full_order",
        minOrder: "0",
        maxUses: "0",
        description: "",
      });
      load();
    } catch (err: unknown) {
      toast.error(getApiErrorMessage(err, "Could not create coupon"));
    } finally {
      setBusy(false);
    }
  };

  const toggleActive = async (row: CouponRow) => {
    try {
      await DataService.patch(`/admin/shop-coupons/${row._id}`, { active: !row.active });
      load();
    } catch (e: unknown) {
      toast.error(getApiErrorMessage(e, "Could not update"));
    }
  };

  const remove = async (id: string) => {
    if (!confirm("Delete this coupon?")) return;
    try {
      await DataService.delete(`/admin/shop-coupons/${id}`);
      toast.success("Deleted");
      load();
    } catch (e: unknown) {
      toast.error(getApiErrorMessage(e, "Could not delete"));
    }
  };

  if (!ready || loading) {
    return <div className="rounded-md border bg-white p-8 text-center text-gray-500">Loading…</div>;
  }

  return (
    <div className="space-y-6">
      <MainTitle title="Shop coupons" />
      <p className="text-sm text-gray-500">Manage discount codes customers can use at checkout. ({app})</p>

      <form onSubmit={create} className="grid gap-3 rounded-md border bg-white p-4 md:grid-cols-3">
        <div className="grid gap-2">
          <Label htmlFor="code">Code</Label>
          <Input
            id="code"
            value={form.code}
            onChange={(e) => setForm((f) => ({ ...f, code: e.target.value }))}
            required
          />
        </div>
        <div className="grid gap-2">
          <Label>Type</Label>
          <Select value={form.type} onValueChange={(v) => setForm((f) => ({ ...f, type: v }))}>
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="percent">Percent</SelectItem>
              <SelectItem value="fixed">Fixed amount</SelectItem>
            </SelectContent>
          </Select>
        </div>
        <div className="grid gap-2">
          <Label htmlFor="value">Value</Label>
          <Input
            id="value"
            type="number"
            min={0}
            value={form.value}
            onChange={(e) => setForm((f) => ({ ...f, value: e.target.value }))}
            required
          />
        </div>
        <div className="grid gap-2">
          <Label>Applies to</Label>
          <Select value={form.applyTo} onValueChange={(v) => setForm((f) => ({ ...f, applyTo: v }))}>
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="full_order">Full order (products + shipping)</SelectItem>
              <SelectItem value="products_only">Products only</SelectItem>
            </SelectContent>
          </Select>
        </div>
        <div className="grid gap-2">
          <Label htmlFor="minOrder">Min order</Label>
          <Input
            id="minOrder"
            type="number"
            min={0}
            value={form.minOrder}
            onChange={(e) => setForm((f) => ({ ...f, minOrder: e.target.value }))}
          />
        </div>
        <div className="grid gap-2">
          <Label htmlFor="maxUses">Max uses (0 = unlimited)</Label>
          <Input
            id="maxUses"
            type="number"
            min={0}
            value={form.maxUses}
            onChange={(e) => setForm((f) => ({ ...f, maxUses: e.target.value }))}
          />
        </div>
        <div className="grid gap-2">
          <Label htmlFor="description">Description</Label>
          <Input
            id="description"
            value={form.description}
            onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))}
          />
        </div>
        <div className="md:col-span-3">
          <Button type="submit" disabled={busy}>
            {busy ? "Creating…" : "Create coupon"}
          </Button>
        </div>
      </form>

      <div className="rounded-md border bg-white">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Code</TableHead>
              <TableHead>Discount</TableHead>
              <TableHead>Applies to</TableHead>
              <TableHead>Uses</TableHead>
              <TableHead>Active</TableHead>
              <TableHead />
            </TableRow>
          </TableHeader>
          <TableBody>
            {rows.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="text-center text-gray-400">
                  No coupons yet.
                </TableCell>
              </TableRow>
            ) : (
              rows.map((r) => (
                <TableRow key={r._id}>
                  <TableCell className="font-mono font-semibold">{r.code}</TableCell>
                  <TableCell>
                    {r.type === "percent" ? `${r.value}%` : `Rs ${r.value}`}
                    {(r.minOrder || 0) > 0 ? ` (min ${r.minOrder})` : ""}
                  </TableCell>
                  <TableCell>
                    {(r.applyTo || "full_order") === "products_only" ? "Products only" : "Full order"}
                  </TableCell>
                  <TableCell>
                    {r.usedCount || 0}
                    {r.maxUses ? ` / ${r.maxUses}` : ""}
                  </TableCell>
                  <TableCell>{r.active ? "Yes" : "No"}</TableCell>
                  <TableCell className="space-x-2 text-right">
                    <Button type="button" size="sm" variant="outline" onClick={() => toggleActive(r)}>
                      {r.active ? "Disable" : "Enable"}
                    </Button>
                    <Button type="button" size="sm" variant="outline" onClick={() => remove(r._id)}>
                      Delete
                    </Button>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}
