"use client";
// src/app/products/new/page.tsx
import { useEffect, useMemo, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { AppShell } from "@/components/layout/AppShell";
import { Input, Select, Textarea, Button, Card, CardHeader, CardTitle, CardContent } from "@/components/ui/index";
import { toast } from "sonner";
import { createProductSchema, ProductFormInput } from "@/lib/validations";
import { useLanguage } from "@/i18n/LanguageContext";

const CURRENCY_OPTS = [
  { value: "USD", label: "USD — US Dollar" },
  { value: "EUR", label: "EUR — Euro" },
  { value: "GBP", label: "GBP — British Pound" },
  { value: "SAR", label: "SAR — Saudi Riyal" },
  { value: "AED", label: "AED — UAE Dirham" },
  { value: "EGP", label: "EGP — Egyptian Pound" },
];

export default function NewProductPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { t } = useLanguage();
  const [isLoading, setIsLoading] = useState(false);
  const [isPrefillLoading, setIsPrefillLoading] = useState(false);

  const productSchemaResolved = useMemo(() => createProductSchema(t), [t]);

  const { register, handleSubmit, reset, formState: { errors } } = useForm<ProductFormInput>({
    resolver: zodResolver(productSchemaResolved),
    defaultValues: { currency: "USD", taxRate: 0, isActive: true },
  });

  useEffect(() => {
    const copyId = searchParams.get("copyId");
    if (!copyId) return;

    let cancelled = false;
    setIsPrefillLoading(true);
    (async () => {
      try {
        const res = await fetch(`/api/products/${copyId}`);
        const json = await res.json();
        if (!res.ok) throw new Error(json.error ?? "Failed");
        const product = json.data;
        if (cancelled) return;

        reset({
          name: `${product.name} (${t("products.copySuffix")})`,
          nameAr: product.nameAr ?? "",
          description: product.description ?? "",
          sku: "",
          price: Number(product.price ?? 0),
          currency: product.currency ?? "USD",
          taxRate: Number(product.taxRate ?? 0),
          isActive: Boolean(product.isActive),
        });
      } catch {
        if (!cancelled) toast.error(t("products.toastDuplicateFailed"));
      } finally {
        if (!cancelled) setIsPrefillLoading(false);
      }
    })();

    return () => { cancelled = true; };
  }, [reset, searchParams, t]);

  const onSubmit = async (data: ProductFormInput) => {
    setIsLoading(true);
    try {
      const res = await fetch("/api/products", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });
      if (!res.ok) throw new Error((await res.json()).error ?? t("toast.failed"));
      toast.success(t("toast.productCreated"));
      router.push("/products");
    } catch (e: any) { toast.error(e.message); }
    finally { setIsLoading(false); }
  };

  return (
    <AppShell breadcrumbs={[{ label: t("nav.products"), href: "/products" }, { label: t("products.new") }]}>
      <div className="w-full min-w-0">
        <div className="mb-6">
          <h1 className="text-xl font-bold text-foreground">{t("products.pageNewTitle")}</h1>
          <p className="text-sm text-muted-foreground mt-0.5">{t("products.pageNewSubtitle")}</p>
        </div>

        <form noValidate onSubmit={handleSubmit(onSubmit)} className="space-y-6">
          <Card>
            <CardHeader><CardTitle>{t("products.formDetails")}</CardTitle></CardHeader>
            <CardContent className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <Input
                label={t("products.nameEn")} required
                placeholder="Enterprise License" className="sm:col-span-2"
                error={errors.name?.message} {...register("name")}
              />
              <Input
                label={t("products.nameArField")}
                placeholder="ترخيص مؤسسي" dir="rtl" className="sm:col-span-2"
                {...register("nameAr")}
              />
              <Input label={t("products.skuLabel")} placeholder="PROD-001" {...register("sku")} />
              <div />
              <Input
                label={t("products.price")} required type="number" step="0.01" min="0"
                placeholder="0.00" error={errors.price?.message}
                {...register("price", { valueAsNumber: true })}
              />
              <Select
                label={t("common.currency")}
                options={CURRENCY_OPTS}
                {...register("currency")}
              />
              <Input
                label={t("products.taxRateLabel")} type="number" step="0.01" min="0" max="100"
                placeholder="0" error={errors.taxRate?.message}
                {...register("taxRate", { valueAsNumber: true })}
              />
            </CardContent>
          </Card>

          <Card>
            <CardHeader><CardTitle>{t("products.formDescription")}</CardTitle></CardHeader>
            <CardContent>
              <Textarea
                placeholder={t("products.descPlaceholder")}
                rows={4} {...register("description")}
              />
            </CardContent>
          </Card>

          <div className="flex justify-end gap-3">
            <Button type="button" variant="outline" onClick={() => router.back()} disabled={isLoading || isPrefillLoading}>{t("common.cancel")}</Button>
            <Button type="submit" loading={isLoading || isPrefillLoading}>{t("products.create")}</Button>
          </div>
        </form>
      </div>
    </AppShell>
  );
}
