"use client";

/** فرم ثبت نظر (برای کاربر واردشده؛ مهمان به صفحه ورود هدایت می‌شود) */
import Link from "next/link";
import { useState, useTransition } from "react";
import { submitReviewAction } from "@/server/actions/account";
import { faNumber } from "@/lib/format";
import { Icon } from "@/components/ui/Icon";
import { reviewSchema, fieldErrors } from "@/validation/common";

export function ReviewForm({ productId, signedIn, productPath }: { productId: number; signedIn: boolean; productPath: string }) {
  const [open, setOpen] = useState(false);
  const [rating, setRating] = useState(0);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [done, setDone] = useState(false);
  const [pending, start] = useTransition();

  if (!signedIn) {
    return (
      <Link href={`/auth?next=${encodeURIComponent(productPath + "#reviews")}`} className="btn-outline w-full">
        <Icon name="edit" size={18} /> برای نوشتن نظر وارد شوید
      </Link>
    );
  }
  if (done) return <p className="rounded-xl bg-mist p-4 text-xs leading-6">نظر شما ثبت شد و پس از بررسی نمایش داده می‌شود. ممنون!</p>;
  if (!open) {
    return (
      <button className="btn-outline w-full" onClick={() => setOpen(true)}>
        <Icon name="edit" size={18} /> نوشتن نظر
      </button>
    );
  }

  return (
    <form
      noValidate
      className="space-y-3"
      onSubmit={(e) => {
        e.preventDefault();
        const fd = new FormData(e.currentTarget);
        const input = { rating, title: String(fd.get("title") ?? ""), body: String(fd.get("body") ?? "") };
        const parsed = reviewSchema.safeParse(input);
        if (!parsed.success) return setErrors(fieldErrors(parsed.error));
        start(async () => {
          const res = await submitReviewAction(productId, parsed.data);
          if (!res.ok) return setErrors(res.errors);
          setDone(true);
        });
      }}
    >
      <fieldset>
        <legend className="label">امتیاز شما</legend>
        <div className="flex gap-1" dir="ltr">
          {[1, 2, 3, 4, 5].map((n) => (
            <button key={n} type="button" onClick={() => setRating(n)} aria-label={`${faNumber(n)} ستاره`} aria-pressed={rating === n} className="p-0.5">
              <svg width="26" height="26" viewBox="0 0 24 24" aria-hidden="true">
                <path d="M12 3.6l2.5 5.2 5.7.8-4.1 4 1 5.6L12 16.5l-5.1 2.7 1-5.6-4.1-4 5.7-.8L12 3.6z" fill={n <= rating ? "currentColor" : "none"} stroke="currentColor" strokeWidth="1.4" />
              </svg>
            </button>
          ))}
        </div>
        {errors.rating && <p className="mt-1 text-xs">⚠ {errors.rating}</p>}
      </fieldset>
      <label className="block">
        <span className="label">عنوان</span>
        <input name="title" className="field" maxLength={80} />
        {errors.title && <p className="mt-1 text-xs">⚠ {errors.title}</p>}
      </label>
      <label className="block">
        <span className="label">متن نظر</span>
        <textarea name="body" className="field h-28 py-3" maxLength={1000} />
        {errors.body && <p className="mt-1 text-xs">⚠ {errors.body}</p>}
      </label>
      {errors._ && <p className="text-xs">⚠ {errors._}</p>}
      <button className="btn-primary w-full" disabled={pending}>{pending ? "در حال ثبت…" : "ثبت نظر"}</button>
    </form>
  );
}
