/* eslint-disable @typescript-eslint/strict-boolean-expressions */
/* eslint-disable @typescript-eslint/no-misused-promises */
/* eslint-disable @typescript-eslint/explicit-function-return-type */

import React, { useEffect, useState } from 'react'
import { zodResolver } from '@hookform/resolvers/zod'
import { useForm, useWatch } from 'react-hook-form'
import { type z } from 'zod'
import { es } from 'date-fns/locale'

import { Button } from '@/components/ui/button'
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'

import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select'

import { Calendar } from '@/components/ui/calendar'
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover'
import { cn } from '@/lib/utils'
import { format } from 'date-fns'
import { CalendarIcon } from 'lucide-react'
import { Checkbox } from '../ui/checkbox'
import { Textarea } from '../ui/textarea'
import { pqrsSchema, requirementTypes } from '@/validations/pqrsScheme'
import { actions } from 'astro:actions'
import { toast } from 'sonner'
import { Toaster } from '../ui/sonner'

function FAQSForm () {
  const form = useForm<z.infer<typeof pqrsSchema>>({
    resolver: zodResolver(pqrsSchema),
    defaultValues: {
      name: '',
      lastName: '',
      email: '',
      cellPhoneNumber: '',
      requirementType: undefined,
      nameOfOfficial: '',
      schedulingDate: undefined,
      city: '',
      headquarters: '',
      description: '',
      vehicleRegistrationNumber: '',
      terms: false
    }
  })

  const [headquartersOptions, setHeadquartersOptions] = useState<any>([])

  const city = useWatch({ name: 'city', control: form.control })

  const sendEmail = async (values: any) => {
    const { error, data } = await actions.sendPQRS(values)
    if (error) throw new Error()
    return data
  }

  const formatDate = (date: Date) => {
    const options: Intl.DateTimeFormatOptions = {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    }
    const formattedDate =
            date.toLocaleDateString('es-ES', options)

    const [day, month, year] = formattedDate.split('/')
    return `${year}-${month}-${day}`
  }

  async function onSubmit (values: z.infer<typeof pqrsSchema>) {
    const formattedDate = formatDate(values.schedulingDate)

    const data = {
      name: values.name,
      lastName: values.lastName,
      email: values.email,
      cellPhoneNumber: values.cellPhoneNumber,
      requirementType: values.requirementType,
      schedulingDate: formattedDate,
      nameOfOfficial: values.nameOfOfficial,
      description: values.description,
      vehicleRegistrationNumber: values.vehicleRegistrationNumber,
      terms: values.terms
    }
    toast.promise(sendEmail(data), {
      loading: 'Enviando...',
      success: (data) => {
        form.reset({
          name: '',
          lastName: '',
          email: '',
          cellPhoneNumber: '',
          requirementType: undefined,
          schedulingDate: undefined,
          nameOfOfficial: '',
          description: '',
          vehicleRegistrationNumber: '',
          terms: false
        })
        return 'Formulario enviado correctamente'
      },
      error: 'Lo sentimos, hubo un error al enviar el formulario.'
    })
  }

  useEffect(() => {
    const requestOptions: RequestInit = {
      method: 'GET',
      redirect: 'follow'
    }

    fetch(`${import.meta.env.PUBLIC_BASE_URL_VML}?ciudad=${city}`, requestOptions)
      .then(async (response) => await response.text())
      .then((result) => {
        setHeadquartersOptions(JSON.parse(result))
      })
      .catch((error) => { console.error(error) })
  }, [city])

  return (
        <div>
            <div className="flex flex-col gap-6 mb-6">
                <h1 className="text-[2rem] font-semibold">PQRSFA.</h1>
                <p className="font-normal">Nuestro interés y compromiso es mejorar la calidad de nuestro servicio cada dia, si tiene una queja, reclamo, sugerencia o felicitaciones lo invitamos a radicar de manera sencilla su solicitud a traves del siguiente formato de <span className="text-primary">PQRSFA</span> </p>
            </div>
            <Form {...form}>
                <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">

                    <div className="flex flex-col gap-8">
                        <div className="flex flex-col lg:flex-row w-full gap-[27px]">
                            <FormField
                                control={form.control}
                                name="name"
                                render={({ field }) => (
                                    <FormItem className="w-full">
                                        <FormControl >
                                            <Input type="text" className=" border-t-0 border-r-0 border-l-0 rounded-none border-b-[1px] border-b-primary outline-none" placeholder="Nombre" {...field} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>

                                )}
                            />
                            <FormField
                                control={form.control}
                                name="lastName"
                                render={({ field }) => (
                                    <FormItem className="w-full">
                                        <FormControl>
                                            <Input type="text" className=" border-t-0 border-r-0 border-l-0 rounded-none border-b-[1px] border-b-primary outline-none" placeholder="Apellido" {...field} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                        </div>
                        <div className="flex flex-col lg:flex-row w-full gap-[27px]">
                            <FormField
                                control={form.control}
                                name="email"
                                render={({ field }) => (
                                    <FormItem className="w-full">
                                        <FormControl >
                                            <Input type="email" className=" border-t-0 border-r-0 border-l-0 rounded-none border-b-[1px] border-b-primary outline-none " placeholder="Correo" {...field} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>

                                )}
                            />
                            <FormField
                                control={form.control}
                                name="cellPhoneNumber"
                                render={({ field }) => (
                                    <FormItem className="w-full">
                                        <FormControl>
                                            <Input type="tel" className=" border-t-0 border-r-0 border-l-0 rounded-none border-b-[1px] border-b-primary outline-none" placeholder="Número Celular" {...field} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>

                                )}
                            />

                        </div>
                        <div className="flex w-full flex-col lg:flex-row gap-[27px]">
                            <div className='w-full flex flex-col gap-4'>
                                <FormLabel className="text-[#7C7C7C]">Tipo de Requerimiento</FormLabel>
                                <FormField
                                    control={form.control}
                                    name="requirementType"
                                    render={({ field }) => (
                                        <Select onValueChange={field.onChange} defaultValue={field.value}>
                                            <SelectTrigger className="w-full border-primary capitalize">
                                                <SelectValue
                                                    placeholder="Seleccionar" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                <SelectGroup>
                                                    {
                                                        requirementTypes.map((requeriment, index) => (
                                                            <SelectItem
                                                                key={index} value={requeriment}
                                                                className="capitalize"
                                                            >{requeriment}</SelectItem>
                                                        ))
                                                    }
                                                </SelectGroup>
                                            </SelectContent>

                                            <FormMessage />
                                        </Select>

                                    )}
                                />
                            </div>
                            <div className='w-full flex flex-col gap-4'>
                                <FormLabel className="text-[#7C7C7C]">Fecha de Incidente</FormLabel>
                                <div className='flex gap-4 justify-between'>
                                    <FormField
                                        control={form.control}
                                        name="schedulingDate"
                                        render={({ field }) => (
                                            <FormItem className="flex flex-col w-full border-primary">

                                                <Popover>
                                                    <PopoverTrigger asChild>
                                                        <FormControl>
                                                            <Button
                                                                variant={'outline'}
                                                                className={cn(
                                                                  'pl-3 text-left font-normal border-primary',
                                                                  !field.value && 'text-muted-foreground'
                                                                )}
                                                            >
                                                                {field.value
                                                                  ? (
                                                                      format(field.value, 'PPP', {
                                                                        locale: es
                                                                      })
                                                                    )
                                                                  : (
                                                                        <span>Seleccionar Fecha</span>
                                                                    )}
                                                                <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
                                                            </Button>
                                                        </FormControl>
                                                    </PopoverTrigger>
                                                    <PopoverContent className="w-auto p-0" align="start">
                                                        <Calendar
                                                            locale={es}
                                                            mode="single"
                                                            selected={field.value}
                                                            onSelect={field.onChange}
                                                            disabled={(date) =>
                                                              date > new Date() || date < new Date('1900-01-01')
                                                            }
                                                            initialFocus
                                                        />
                                                    </PopoverContent>
                                                </Popover>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                </div>

                            </div>

                        </div>
                        <div className="flex w-full flex-col lg:flex-row gap-[27px]">
                            <div className="w-full flex flex-col gap-4">
                                <FormLabel className="text-[#7C7C7C]">Ciudad</FormLabel>
                                <FormField
                                    control={form.control}
                                    name="city"
                                    render={({ field }) => (
                                        <Select onValueChange={field.onChange} defaultValue={field.value}>
                                            <SelectTrigger className="w-full border-primary">
                                                <SelectValue placeholder="Seleccionar" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                <SelectGroup>
                                                    <SelectItem value="BOGOTA">Bogotá</SelectItem>
                                                    <SelectItem value="CALI">Cali</SelectItem>
                                                </SelectGroup>
                                            </SelectContent>
                                            <FormMessage />

                                        </Select>
                                    )}
                                />
                            </div>
                            <div className="w-full flex flex-col gap-4">
                                <FormLabel className="text-[#7C7C7C]">Sede</FormLabel>
                                <FormField
                                    control={form.control}
                                    name="headquarters"
                                    render={({ field }) => (
                                        <Select onValueChange={field.onChange} defaultValue={field.value} >
                                            <SelectTrigger className="w-full border-primary">
                                                <SelectValue placeholder="Seleccionar" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                <SelectGroup>
                                                    {headquartersOptions.length > 0
                                                      ? headquartersOptions.map((option: any) => (
                                                            <SelectItem key={option.name} value={option.name}>{option.name}</SelectItem>
                                                      ))
                                                      : <SelectLabel>No hay sedes disponibles</SelectLabel>
                                                    }
                                                </SelectGroup>
                                            </SelectContent>
                                            <FormMessage />

                                        </Select>

                                    )}
                                />
                            </div>

                        </div>
                        <div>
                            <FormField
                                control={form.control}
                                name="nameOfOfficial"
                                render={({ field }) => (
                                    <FormItem className="w-full">
                                        <FormControl >
                                            <Input type="text" className=" border-t-0 border-r-0 border-l-0 rounded-none border-b-[1px] border-b-primary outline-none" placeholder="Nombre del funcionario (si lo conoce)" {...field} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                        </div>
                        <div>
                            <FormField
                                control={form.control}
                                name="description"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormControl>
                                            <Textarea
                                                placeholder="Describa los hechos sucedidos..."
                                                className="resize-none border-primary h-40 outline-none"
                                                {...field}
                                            />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>

                                )}
                            />
                        </div>
                        <div>
                            <FormField
                                control={form.control}
                                name="vehicleRegistrationNumber"
                                render={({ field }) => (
                                    <FormItem className="w-[50%]">
                                        <FormControl >
                                            <Input type="text" className=" border-t-0 border-r-0 border-l-0 rounded-none border-b-[1px] border-b-primary outline-none" placeholder="Placa del vehículo" {...field} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>

                                )}
                            />
                        </div>

                    </div>

                    <FormField
                        control={form.control}
                        name="terms"
                        render={({ field }) => (
                            <FormItem className="flex flex-row items-start space-x-3 space-y-0 ">
                                <FormControl>
                                    <Checkbox
                                        checked={field.value}
                                        onCheckedChange={field.onChange}
                                    />
                                </FormControl>
                                <div className="space-y-1 leading-none">
                                    <FormLabel className="text-[#7C7C7C]">
                                        Acepto todos los   <a className="text-primary opacity-80" href="/assets/files/PD-DA-03-aviso-de-privacidad.pdf" target="_blank">términos y condiciones</a> y la <a className="text-primary opacity-80" href="/assets/files/PD-DA-03-aviso-de-privacidad.pdf" target="_blank">política de privacidad</a>
                                    </FormLabel>
                                    <FormMessage />
                                </div>
                            </FormItem>
                        )}
                    />
                    <Button type="submit">Enviar</Button>
                </form>
            </Form>
            <Toaster richColors position="top-center" style={{ backgroundColor: 'white' }} />
        </div>
  )
}

export default FAQSForm
