"use client";

import { useState } from "react";
import { useAction, useQuery, useConvexAuth } from "convex/react";
import { api } from "../../../../../../convex/_generated/api";
import type { Id } from "../../../../../../convex/_generated/dataModel";
import { Form, TextField, Label, Input, TextArea, FieldError, Button, Spinner, toast } from "@heroui/react";
import { StarRatingInput } from "./StarRatingInput";
import Link from "next/link";

export function ReviewForm({ productId }: { productId: Id<"products"> }) {
    const { isAuthenticated } = useConvexAuth();
    const hasReviewed = useQuery(api.reviews.hasUserReviewed, { productId });
    const submitAndRecalculate = useAction(api.reviews.submitAndRecalculate);

    const [rating, setRating] = useState<number>(0);
    const [isSubmitting, setIsSubmitting] = useState(false);

    // Loading auth state
    if (isAuthenticated === undefined || (isAuthenticated && hasReviewed === undefined)) {
        return <div className="mt-8 h-32 animate-pulse rounded-lg bg-[var(--surface-secondary)]" />;
    }

    // Not signed in
    if (!isAuthenticated) {
        return (
            <div className="mt-8 border-t border-[var(--separator)] pt-8">
                <h3 className="text-lg font-bold font-[family-name:var(--font-fraunces)] text-[var(--foreground)] mb-4">
                    Write a Review
                </h3>
                <p className="mb-4 text-sm text-[var(--muted)]">
                    Please sign in to share your experience with this product.
                </p>
                <Link
                    href="/sign-in"
                    className="inline-flex items-center justify-center rounded-lg bg-[var(--brand-dark)] px-4 py-2 text-sm font-medium text-white w-full md:w-auto"
                >
                    Sign In
                </Link>
            </div>
        );
    }

    // Already reviewed
    if (hasReviewed) {
        return (
            <div className="mt-8 border-t border-[var(--separator)] pt-8">
                <h3 className="text-lg font-bold font-[family-name:var(--font-fraunces)] text-[var(--foreground)] mb-2">
                    You&apos;ve already reviewed this product
                </h3>
                <p className="text-sm text-[var(--muted)]">
                    Thank you for sharing your experience! Your review is helping other pet parents.
                </p>
            </div>
        );
    }

    const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        if (rating === 0) {
            toast.danger("Please select a rating to submit.");
            return;
        }

        const formData = new FormData(e.currentTarget);
        const title = formData.get("title") as string;
        const content = formData.get("content") as string;

        setIsSubmitting(true);
        try {
            await submitAndRecalculate({ productId, rating, title, content });
            toast.success("Thanks for your review! It will appear after moderation.");
            e.currentTarget.reset();
            setRating(0);
        } catch (err: unknown) {
            const message = err instanceof Error ? err.message : "Failed to submit review.";
            toast.danger(message);
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <div className="mt-8 border-t border-[var(--separator)] pt-8">
            <h3 className="text-lg font-bold font-[family-name:var(--font-fraunces)] text-[var(--foreground)] mb-6">
                Write a Review
            </h3>

            <Form onSubmit={handleSubmit} className="flex flex-col gap-5 max-w-2xl w-full">
                <div className="flex flex-col gap-2">
                    <label className="text-sm font-medium text-[var(--foreground)]">
                        Your rating <span className="text-danger">*</span>
                    </label>
                    <StarRatingInput value={rating} onChange={setRating} />
                </div>

                {/* TextField wraps Label + Input + FieldError — isRequired/validate live on TextField, not Input */}
                <TextField
                    isRequired
                    name="title"
                    minLength={3}
                    maxLength={100}
                    validate={(val: string) => {
                        if (val && val.length < 3) return "Title must be at least 3 characters";
                    }}
                    className="flex flex-col gap-1"
                >
                    <Label className="text-sm font-medium text-[var(--foreground)]">Review title</Label>
                    <Input placeholder="Summarize your experience" className="bg-[var(--surface)]" />
                    <FieldError className="text-xs text-danger" />
                </TextField>

                {/* TextArea is a bare primitive — wrap in TextField for validation/label support */}
                <TextField
                    isRequired
                    name="content"
                    minLength={10}
                    maxLength={2000}
                    validate={(val: string) => {
                        if (val && val.length < 10) return "Review must be at least 10 characters";
                    }}
                    className="flex flex-col gap-1"
                >
                    <Label className="text-sm font-medium text-[var(--foreground)]">Your review</Label>
                    <TextArea
                        rows={4}
                        placeholder="What did you like or dislike?"
                        className="bg-[var(--surface)]"
                    />
                    <FieldError className="text-xs text-danger" />
                </TextField>

                {/* isPending (not isLoading); spinner via render-prop children */}
                <Button
                    type="submit"
                    isPending={isSubmitting}
                    className="bg-[var(--brand-dark)] text-white w-full md:w-auto md:self-start mt-2"
                >
                    {({ isPending }: { isPending: boolean }) => (
                        <>
                            {isPending ? <Spinner color="current" size="sm" /> : null}
                            Submit Review
                        </>
                    )}
                </Button>
            </Form>
        </div>
    );
}
