"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

type Initial = {
  code: string;
  type: string;
  value: number;
  expiresAt: string;
  maxRedemptions: number;
  active: boolean;
};

export function CouponForm({
  couponId,
  initial,
}: {
  couponId?: string;
  initial?: Initial;
}) {
  const router = useRouter();
  const [code, setCode] = useState(initial?.code ?? "");
  const [type, setType] = useState(initial?.type ?? "PERCENT");
  const [value, setValue] = useState(String(initial?.value ?? 10));
  const [expiresAt, setExpiresAt] = useState(
    initial?.expiresAt ?? new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().slice(0, 16)
  );
  const [maxRedemptions, setMaxRedemptions] = useState(String(initial?.maxRedemptions ?? 100));
  const [active, setActive] = useState(initial?.active ?? true);
  const [loading, setLoading] = useState(false);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    const body = {
      code,
      type,
      value: Number(value),
      expiresAt: new Date(expiresAt).toISOString(),
      maxRedemptions: Math.max(0, parseInt(maxRedemptions, 10) || 0),
      active,
    };
    const url = couponId ? `/api/admin/coupons/${couponId}` : "/api/admin/coupons";
    const res = await fetch(url, {
      method: couponId ? "PATCH" : "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    });
    setLoading(false);
    if (res.ok) router.push("/admin/coupons");
    else router.refresh();
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div>
        <Label>کد</Label>
        <Input value={code} onChange={(e) => setCode(e.target.value)} className="mt-1" required />
      </div>
      <div>
        <Label>نوع</Label>
        <select
          value={type}
          onChange={(e) => setType(e.target.value)}
          className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm mt-1"
        >
          <option value="PERCENT">درصد</option>
          <option value="FIXED">مبلغ ثابت</option>
        </select>
      </div>
      <div>
        <Label>مقدار {type === "PERCENT" ? "(درصد)" : "(مبلغ)"}</Label>
        <Input
          type="number"
          value={value}
          onChange={(e) => setValue(e.target.value)}
          className="mt-1"
          min={0}
        />
      </div>
      <div>
        <Label>تاریخ انقضا</Label>
        <Input
          type="datetime-local"
          value={expiresAt}
          onChange={(e) => setExpiresAt(e.target.value)}
          className="mt-1"
        />
      </div>
      <div>
        <Label>حداکثر استفاده</Label>
        <Input
          type="number"
          value={maxRedemptions}
          onChange={(e) => setMaxRedemptions(e.target.value)}
          className="mt-1"
          min={0}
        />
      </div>
      <div className="flex items-center gap-2">
        <input
          type="checkbox"
          id="active"
          checked={active}
          onChange={(e) => setActive(e.target.checked)}
        />
        <Label htmlFor="active">فعال</Label>
      </div>
      <Button type="submit" disabled={loading}>
        {loading ? "در حال ذخیره..." : couponId ? "بروزرسانی" : "ایجاد"}
      </Button>
    </form>
  );
}
