"use client";

import { type FormEvent, useState } from "react";
import { Frown, Laugh, Meh, Smile, Star } from "lucide-react";
import { toast } from "react-toastify";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Textarea } from "@/components/ui/textarea";
import { apiRequest, apiUrl } from "@/lib/api";
import { getLocalizedApiMessage } from "@/lib/api-message";

const satisfactionOptions = [
  {
    value: 1,
    label: "Very poor",
    icon: Frown,
    activeClass: "border-red-500 bg-red-500 text-white shadow-sm",
    hoverClass: "hover:border-red-500 hover:text-red-600",
  },
  {
    value: 2,
    label: "Poor",
    icon: Frown,
    activeClass: "border-orange-500 bg-orange-500 text-white shadow-sm",
    hoverClass: "hover:border-orange-500 hover:text-orange-600",
  },
  {
    value: 3,
    label: "Average",
    icon: Meh,
    activeClass: "border-yellow-500 bg-yellow-500 text-white shadow-sm",
    hoverClass: "hover:border-yellow-500 hover:text-yellow-600",
  },
  {
    value: 4,
    label: "Good",
    icon: Smile,
    activeClass: "border-emerald-500 bg-emerald-500 text-white shadow-sm",
    hoverClass: "hover:border-emerald-500 hover:text-emerald-600",
  },
  {
    value: 5,
    label: "Excellent",
    icon: Laugh,
    activeClass: "border-sky-500 bg-sky-500 text-white shadow-sm",
    hoverClass: "hover:border-sky-500 hover:text-sky-600",
  },
];

type GuideReviewFormProps = {
  userUuid: string;
  onReviewSubmitted?: () => void;
};

type ReviewErrors = Partial<
  Record<
    | "customerName"
    | "customerEmail"
    | "rating"
    | "satisfaction"
    | "feedback"
    | "accepted",
    string
  >
>;

export function GuideReviewForm({
  userUuid,
  onReviewSubmitted,
}: GuideReviewFormProps) {
  const [customerName, setCustomerName] = useState("");
  const [customerEmail, setCustomerEmail] = useState("");
  const [rating, setRating] = useState(0);
  const [satisfaction, setSatisfaction] = useState(0);
  const [recommendation, setRecommendation] = useState("yes");
  const [feedback, setFeedback] = useState("");
  const [accepted, setAccepted] = useState(false);
  const [errors, setErrors] = useState<ReviewErrors>({});
  const [isSubmitting, setIsSubmitting] = useState(false);

  const validateForm = () => {
    const nextErrors: ReviewErrors = {};
    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

    if (!customerName.trim()) {
      nextErrors.customerName = "Name is required.";
    }

    if (!customerEmail.trim()) {
      nextErrors.customerEmail = "Email address is required.";
    } else if (!emailPattern.test(customerEmail.trim())) {
      nextErrors.customerEmail = "Enter a valid email address.";
    }

    if (!rating) {
      nextErrors.rating = "Overall rating is required.";
    }

    if (!satisfaction) {
      nextErrors.satisfaction = "Satisfaction level is required.";
    }

    if (!feedback.trim()) {
      nextErrors.feedback = "Feedback is required.";
    }

    if (!accepted) {
      nextErrors.accepted = "Please agree to the terms and conditions.";
    }

    setErrors(nextErrors);
    return Object.keys(nextErrors).length === 0;
  };

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    if (!userUuid) {
      toast.error("Guide user uuid is missing.");
      return;
    }

    if (!validateForm()) {
      return;
    }

    setIsSubmitting(true);

    try {
      const response = await apiRequest(apiUrl("/add-review"), {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          user_uuid: userUuid,
          customer_name: customerName.trim(),
          customer_email: customerEmail.trim(),
          rating,
          satisfaction,
          feedback: feedback.trim(),
          recommend: recommendation === "yes",
          is_agreed: accepted,
        }),
      });

      const result = await response.json().catch(() => ({}));

      if (!response.ok) {
        toast.error(
          getLocalizedApiMessage(result, "Review submission failed."),
        );
        return;
      }

      toast.success(
        getLocalizedApiMessage(result, "Review submitted successfully."),
      );
      setCustomerName("");
      setCustomerEmail("");
      setRating(0);
      setSatisfaction(0);
      setRecommendation("yes");
      setFeedback("");
      setAccepted(false);
      setErrors({});
      onReviewSubmitted?.();
    } catch {
      toast.error("Unable to connect to the review server.");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Card className="overflow-hidden border-[var(--theme-border)] bg-white shadow-sm">
      <CardHeader className="border-b border-[var(--theme-border)]">
        <CardTitle className="text-xl font-black text-foreground">
          Add Your Review
        </CardTitle>
        <p className="text-sm font-medium text-muted-foreground">
          We appreciate your feedback about this guide experience.
        </p>
      </CardHeader>
      <CardContent className="p-5">
        <form onSubmit={handleSubmit} className="space-y-5" noValidate>
          <div className="grid gap-4 md:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="review-name" className="font-bold">
                Your Name
              </Label>
              <Input
                id="review-name"
                value={customerName}
                onChange={(event) => setCustomerName(event.target.value)}
                placeholder="Enter your name"
                className="h-11 rounded-xl border-[var(--theme-border-soft)] bg-[var(--theme-surface)]"
              />
              {errors.customerName && (
                <p className="text-xs font-semibold text-red-600">
                  {errors.customerName}
                </p>
              )}
            </div>
            <div className="space-y-2">
              <Label htmlFor="review-email" className="font-bold">
                Email Address
              </Label>
              <Input
                id="review-email"
                type="email"
                value={customerEmail}
                onChange={(event) => setCustomerEmail(event.target.value)}
                placeholder="example@domain.com"
                className="h-11 rounded-xl border-[var(--theme-border-soft)] bg-[var(--theme-surface)]"
              />
              {errors.customerEmail && (
                <p className="text-xs font-semibold text-red-600">
                  {errors.customerEmail}
                </p>
              )}
            </div>
          </div>

          <div className="grid gap-5 md:grid-cols-2">
            <div className="space-y-2">
              <div>
                <Label className="font-bold">Overall Rating</Label>
                <p className="text-xs font-medium text-muted-foreground">
                  How would you rate your overall experience?
                </p>
              </div>
              <div className="flex gap-1.5">
                {[1, 2, 3, 4, 5].map((value) => (
                  <button
                    key={value}
                    type="button"
                    onClick={() => setRating(value)}
                    className="rounded-full p-1 transition hover:bg-[var(--theme-surface-strong)]"
                    aria-label={`${value} star rating`}
                  >
                    <Star
                      className={`h-7 w-7 ${
                        value <= rating
                          ? "fill-yellow-400 text-yellow-400"
                          : "fill-slate-200 text-slate-200"
                      }`}
                    />
                  </button>
                ))}
              </div>
              {errors.rating && (
                <p className="text-xs font-semibold text-red-600">
                  {errors.rating}
                </p>
              )}
            </div>

            <div className="space-y-2">
              <div>
                <Label className="font-bold">Satisfaction Level</Label>
                <p className="text-xs font-medium text-muted-foreground">
                  Are you happy with this guide service?
                </p>
              </div>
              <div className="flex flex-wrap gap-2">
                {satisfactionOptions.map((option) => {
                  const Icon = option.icon;
                  const active = satisfaction === option.value;

                  return (
                    <button
                      key={option.value}
                      type="button"
                      title={option.label}
                      onClick={() => setSatisfaction(option.value)}
                      className={`flex h-12 w-12 items-center justify-center rounded-full border transition ${
                        active
                          ? option.activeClass
                          : `border-[var(--theme-border-soft)] bg-[var(--theme-surface)] text-muted-foreground ${option.hoverClass}`
                      }`}
                    >
                      <Icon className="h-6 w-6" />
                    </button>
                  );
                })}
              </div>
              {errors.satisfaction && (
                <p className="text-xs font-semibold text-red-600">
                  {errors.satisfaction}
                </p>
              )}
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="review-feedback" className="font-bold">
              Feedback
            </Label>
            <Textarea
              id="review-feedback"
              value={feedback}
              onChange={(event) => setFeedback(event.target.value)}
              placeholder="Please share your experience with us"
              rows={4}
              className="rounded-xl border-[var(--theme-border-soft)] bg-[var(--theme-surface)]"
            />
            {errors.feedback && (
              <p className="text-xs font-semibold text-red-600">
                {errors.feedback}
              </p>
            )}
          </div>

          <div className="space-y-3">
            <Label className="font-bold">
              Would you recommend this guide to a friend?
            </Label>
            <RadioGroup
              value={recommendation}
              onValueChange={setRecommendation}
              className="gap-2"
            >
              {[
                ["yes", "Yes"],
                ["no", "No"],
              ].map(([value, label]) => (
                <label
                  key={value}
                  className="flex items-center gap-2 text-sm font-medium"
                >
                  <RadioGroupItem value={value} />
                  {label}
                </label>
              ))}
            </RadioGroup>
          </div>

          <label className="flex items-center gap-2 text-sm font-medium text-muted-foreground">
            <Checkbox
              checked={accepted}
              onCheckedChange={(value) => setAccepted(Boolean(value))}
            />
            I agree to the terms and conditions.
          </label>
          {errors.accepted && (
            <p className="text-xs font-semibold text-red-600">
              {errors.accepted}
            </p>
          )}

          <div className="flex justify-end">
            <Button
              type="submit"
              disabled={isSubmitting}
              className="rounded-xl bg-[var(--theme-primary)] px-6 font-black text-white hover:bg-[var(--theme-primary)]/90"
            >
              {isSubmitting ? "Submitting..." : "Submit Review"}
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}
