'use client';

import { zodResolver } from '@hookform/resolvers/zod';
import { Loader2, Plus, Star } from 'lucide-react';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';

import { useTextController } from '@/shared/language';
import { Button } from '@/shared/shadcn-ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/shared/shadcn-ui/dialog';
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/shared/shadcn-ui/form';
import { Input } from '@/shared/shadcn-ui/input';
import { Textarea } from '@/shared/shadcn-ui/textarea';

import { useCreateReviewMutation } from '../api/reviews.api';
import { ReviewFormValues, reviewSchema } from '../model/review-form.schema';

export function ReviewForm() {
  const { t } = useTextController();
  const [openReviewFormDialog, setOpenReviewFormDialog] = useState(false);
  const [hoveredStar, setHoveredStar] = useState(0);

  const [createReview, { isLoading: isSubmitting }] = useCreateReviewMutation();

  const form = useForm<ReviewFormValues>({
    resolver: zodResolver(reviewSchema),
    defaultValues: {
      name: '',
      rating: 0,
      reviewMessage: '',
    },
  });

  const onSubmit = async (data: ReviewFormValues) => {
    try {
      await createReview(data);

      toast.success(t('about.review-form.dialog.successResponse'), {
        duration: 5000,
      });

      form.reset();
      setOpenReviewFormDialog(false);
    } catch (error) {
      toast.error(t('about.review-form.dialog.errorResponse'), {
        duration: 5000,
      });
    }
  };

  const StarRating = ({
    value,
    onChange,
  }: {
    value: number;
    onChange: (value: number) => void;
  }) => {
    return (
      <>
        {[1, 2, 3, 4, 5].map((star) => (
          <button
            key={star}
            type='button'
            onClick={() => onChange(star)}
            onMouseEnter={() => setHoveredStar(star)}
            onMouseLeave={() => setHoveredStar(0)}
            className='cursor-pointer transition-transform hover:scale-110 focus:outline-none'
            aria-label={`Rate ${star} stars out of 5`}
          >
            <Star
              className={`h-8 w-8 ${
                star <= (hoveredStar || value)
                  ? 'fill-yellow-400 text-yellow-400'
                  : 'text-gray-300'
              } transition-colors`}
            />
          </button>
        ))}
      </>
    );
  };

  return (
    <div>
      <Dialog
        open={openReviewFormDialog}
        onOpenChange={setOpenReviewFormDialog}
      >
        <DialogTrigger asChild>
          <Button className='flex shadow-lg transition-all duration-300 hover:scale-105'>
            <Plus />
            <span>{t('common.buttons.addReview')}</span>
          </Button>
        </DialogTrigger>
        <DialogContent className='overflow-hidden rounded-xl border-none bg-white/95 p-0 shadow-xl backdrop-blur-sm sm:max-w-[500px]'>
          <div className='p-6'>
            <DialogHeader className='pb-4'>
              <DialogTitle className='text-center text-2xl font-bold'>
                {t('about.review-form.dialog.title')}
              </DialogTitle>
              <DialogDescription className='pt-2 text-center'>
                {t('about.review-form.dialog.description')}
              </DialogDescription>
            </DialogHeader>

            <Form {...form}>
              <form
                onSubmit={form.handleSubmit(onSubmit)}
                className='space-y-6'
              >
                <FormField
                  control={form.control}
                  name='name'
                  render={({ field }) => (
                    <FormItem className='flex flex-col'>
                      <FormLabel>
                        {t('about.review-form.dialog.field.name')}
                      </FormLabel>
                      <FormControl>
                        <Input
                          placeholder={t(
                            'about.review-form.dialog.field.name.placeholder',
                          )}
                          {...field}
                          className='bg-white/50'
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name='rating'
                  render={({ field }) => (
                    <FormItem className='space-y-3'>
                      <FormLabel className='block'>
                        {t('about.review-form.dialog.field.rating')}
                      </FormLabel>
                      <FormControl>
                        <StarRating
                          value={field.value}
                          onChange={(value) => field.onChange(value)}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name='reviewMessage'
                  render={({ field }) => (
                    <FormItem className='flex flex-col'>
                      <FormLabel>
                        {t('about.review-form.dialog.field.reviewMessage')}
                      </FormLabel>
                      <FormControl>
                        <Textarea
                          placeholder={t(
                            'about.review-form.dialog.field.reviewMessage.placeholder',
                          )}
                          className='min-h-[120px] resize-none bg-white/50'
                          {...field}
                        />
                      </FormControl>
                      <FormDescription>
                        {t('about.review-form.dialog.noteMessage')}
                      </FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <DialogFooter className='pt-2'>
                  <Button
                    type='submit'
                    className='w-full'
                    disabled={isSubmitting}
                  >
                    {isSubmitting ? (
                      <>
                        <Loader2 className='mr-2 h-4 w-4 animate-spin' />
                        Отправка...
                      </>
                    ) : (
                      t('common.buttons.sendReview')
                    )}
                  </Button>
                </DialogFooter>
              </form>
            </Form>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
