'use client'

import React, { useState } from 'react'
import { useForm } from 'react-hook-form'
import { z } from 'zod'
import { zodResolver } from '@hookform/resolvers/zod'
import { Order } from '@/lib/types/order'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '../shadcn/ui/card'
import { Separator } from '../shadcn/ui/separator'
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '../shadcn/ui/form'
import * as reviewService from '@/lib/services/review-service'
import { useModalAlert } from '@/lib/hooks/useModalAlert'
import { Input } from '../shadcn/ui/input'
import { Popover, PopoverContent, PopoverTrigger } from '../shadcn/ui/popover'
import { Button } from '../shadcn/ui/button'
import { cn } from '@/lib/utils/tw-merge'
import { Country } from '@/lib/types/country'
import { Check, ChevronsUpDown, Loader2, Star } from 'lucide-react'
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from '../shadcn/ui/command'
import { Textarea } from '../shadcn/ui/textarea'
import { ModalAlert } from '../modal/ModalAlert'

// Define the form validation schema
const reviewSchema = z.object({
  name: z.string().min(2, { message: 'Name must be at least 2 characters' }),
  country: z.string().min(1, { message: 'Please select a country' }),
  rating: z.number().min(1, { message: 'Please select a rating' }).max(5),
  message: z
    .string()
    .min(10, { message: 'Message must be at least 10 characters' }),
})

type ReviewFormValues = z.infer<typeof reviewSchema>

interface ReviewFormProps {
  order: Order
  productId: number
  productCategory: 'fastboat' | 'activity' | 'tour_package'
  countries: Country[]
}

const ReviewForm: React.FC<ReviewFormProps> = ({
  order,
  productCategory,
  productId,
  countries,
}) => {
  const [hoveredRating, setHoveredRating] = useState(0)
  const form = useForm<ReviewFormValues>({
    resolver: zodResolver(reviewSchema),
    defaultValues: {
      name: order?.billing_name || '',
      country: '',
      rating: 0,
      message: '',
    },
  })
  const [submitStatus, setSubmitStatus] = useState<
    'idle' | 'loading' | 'success' | 'error'
  >('idle')
  const {
    showSuccessAlert,
    showErrorAlert,
    alertOptions,
    open: modalAlertOpened,
    setOpen: setModalAlertOpened,
  } = useModalAlert()
  const [open, setOpen] = useState(false)

  const handleSubmitForm = async (data: ReviewFormValues) => {
    try {
      setSubmitStatus('loading')

      const requiredField: Required<ReviewFormValues> = {
        name: data.name,
        country: data.country,
        rating: data.rating,
        message: data.message,
      }

      await reviewService.store({
        ...requiredField,
        product_category: productCategory,
        product_id: productId,
        merchant_id: order.user_id,
      })

      form.reset()
      setSubmitStatus('success')
      showSuccessAlert('Review Submitted', 'Thank you for your feedback!')
    } catch (error) {
      setSubmitStatus('error')
      showErrorAlert('Oops! Something Went Wrong', error.message)
    }
  }

  // Function to get star rating color based on value
  const getStarColor = (
    starPosition: number,
    currentValue: number,
    hovered: number,
  ) => {
    if ((hovered || currentValue) >= starPosition) {
      return '#FFD700' // Gold color for selected/hovered stars
    }
    return 'none' // No fill for unselected stars
  }

  return (
    <React.Fragment>
      <Card className="w-full border-none shadow-lg overflow-hidden">
        <div className="bg-gradient-to-r from-blue-500 to-teal-400 h-2" />
        <CardHeader className="pb-3">
          <CardTitle className="text-xl">Write Your Review</CardTitle>
          <CardDescription className="text-slate-500">
            Tell us about your experience with this boat service
          </CardDescription>
        </CardHeader>

        <Separator className="mb-6" />

        <CardContent className="pb-8">
          <Form {...form}>
            <form
              onSubmit={form.handleSubmit(handleSubmitForm)}
              className="space-y-6"
            >
              <div className="grid grid-cols-1 place-items-start md:grid-cols-2 gap-6">
                {/* Name Field */}
                <FormField
                  control={form.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem className="flex flex-col w-full">
                      <FormLabel className="text-gray-700">Name</FormLabel>
                      <FormControl>
                        <Input
                          placeholder="Your name"
                          {...field}
                          className="border-gray-200 focus-visible:ring-blue-500 h-11"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                {/* Nationality */}
                <FormField
                  control={form.control}
                  name={'country'}
                  render={({ field }) => (
                    <FormItem className="flex flex-col w-full">
                      <FormLabel>Country</FormLabel>
                      <Popover
                        open={open}
                        onOpenChange={(open) => setOpen(open)}
                      >
                        <PopoverTrigger asChild>
                          <FormControl>
                            <Button
                              variant="outline"
                              role="combobox"
                              className={cn(
                                !field.value && 'text-muted-foreground',
                                '!w-full flex justify-between h-11',
                              )}
                            >
                              {field.value
                                ? countries?.find(
                                    (country) =>
                                      country.en_short_name === field.value,
                                  )?.en_short_name
                                : 'Select Country'}
                              <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                            </Button>
                          </FormControl>
                        </PopoverTrigger>

                        <PopoverContent
                          className="w-[calc(100vw-2rem)] sm:w-auto max-w-[calc(100vw-2rem)] p-0"
                          align="start"
                        >
                          <Command className="w-full">
                            <CommandInput placeholder="Search nationality..." />
                            <CommandList>
                              <CommandEmpty>No nationality found.</CommandEmpty>
                              <CommandGroup>
                                {countries?.map((country) => (
                                  <CommandItem
                                    value={country.en_short_name}
                                    key={country.id}
                                    onSelect={() => {
                                      form.setValue(
                                        'country',
                                        country.en_short_name,
                                      )

                                      setOpen(false)
                                    }}
                                  >
                                    {country.en_short_name}
                                    <Check
                                      className={cn(
                                        'ml-auto',
                                        country.en_short_name === field.value
                                          ? 'opacity-100'
                                          : 'opacity-0',
                                      )}
                                    />
                                  </CommandItem>
                                ))}
                              </CommandGroup>
                            </CommandList>
                          </Command>
                        </PopoverContent>
                      </Popover>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              {/* Rating Field - Improved visual design */}
              <FormField
                control={form.control}
                name="rating"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-gray-700">Rating</FormLabel>
                    <FormControl>
                      <div className="flex items-center gap-1 bg-gray-50 p-3 rounded-md justify-center">
                        {[1, 2, 3, 4, 5].map((star) => (
                          <button
                            key={star}
                            type="button"
                            onClick={() =>
                              form.setValue('rating', star, {
                                shouldValidate: true,
                              })
                            }
                            onMouseEnter={() => setHoveredRating(star)}
                            onMouseLeave={() => setHoveredRating(0)}
                            className="focus:outline-none p-1 transition-transform hover:scale-110"
                          >
                            <Star
                              className="w-8 h-8"
                              fill={getStarColor(
                                star,
                                field.value,
                                hoveredRating,
                              )}
                              stroke={
                                field.value >= star ? '#FFD700' : '#9CA3AF'
                              }
                              strokeWidth={1.5}
                            />
                          </button>
                        ))}
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Message Field */}
              <FormField
                control={form.control}
                name="message"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-gray-700">Your Review</FormLabel>
                    <FormControl>
                      <Textarea
                        placeholder="Share your experience..."
                        className="resize-none border-gray-200 focus-visible:ring-blue-500 min-h-32"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Submit Button - More attractive styling */}
              <Button
                type="submit"
                className="w-full bg-gradient-to-r from-blue-600 to-teal-500 hover:from-blue-700 hover:to-teal-600 text-white font-medium py-6 transition-all shadow-md hover:shadow-lg"
                disabled={
                  form.formState.isSubmitting || submitStatus === 'loading'
                }
              >
                {submitStatus === 'loading' && (
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                )}
                {submitStatus === 'loading'
                  ? 'Submitting...'
                  : 'Submit Your Review'}
              </Button>
            </form>
          </Form>
        </CardContent>
      </Card>

      <ModalAlert
        open={modalAlertOpened}
        onOpenChange={(open) => {
          setModalAlertOpened(open)
        }}
        {...alertOptions}
      />
    </React.Fragment>
  )
}

export default ReviewForm
