"use client"

import * as React from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { Check, ChevronsUpDown } from "lucide-react"
import i18nIsoCountries from "i18n-iso-countries"
import enLocale from "i18n-iso-countries/langs/en.json"
import koLocale from "i18n-iso-countries/langs/ko.json"
import { cn } from "@/lib/utils"

import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover"
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command"

// react-hook-form + shadcn/ui Form
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"

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

import { createVendorCandidateSchema, CreateVendorCandidateSchema } from "../validations"
import { createVendorCandidate } from "../service"
import { vendorCandidates } from "@/db/schema/vendors"

// Register locales for countries
i18nIsoCountries.registerLocale(enLocale)
i18nIsoCountries.registerLocale(koLocale)

// Generate country array
const locale = "ko"
const countryMap = i18nIsoCountries.getNames(locale, { select: "official" })
const countryArray = Object.entries(countryMap).map(([code, label]) => ({
  code,
  label,
}))

export function AddCandidateDialog() {
  const [open, setOpen] = React.useState(false)
  const [isSubmitting, setIsSubmitting] = React.useState(false)

  // react-hook-form 세팅
  const form = useForm<CreateVendorCandidateSchema>({
    resolver: zodResolver(createVendorCandidateSchema),
    defaultValues: {
      companyName: "",
      contactEmail: "",
      contactPhone: "",
      country: "",
      source: "",
      status: "COLLECTED", // Default status set to COLLECTED
    },
  })

  async function onSubmit(data: CreateVendorCandidateSchema) {
    setIsSubmitting(true)
    try {
      const result = await createVendorCandidate(data)
      if (result.error) {
        alert(`에러: ${result.error}`)
        return
      }
      // 성공 시 모달 닫고 폼 리셋
      form.reset()
      setOpen(false)
    } catch (error) {
      console.error("Failed to create vendor candidate:", error)
      alert("An unexpected error occurred")
    } finally {
      setIsSubmitting(false)
    }
  }

  function handleDialogOpenChange(nextOpen: boolean) {
    if (!nextOpen) {
      form.reset()
    }
    setOpen(nextOpen)
  }

  return (
    <Dialog open={open} onOpenChange={handleDialogOpenChange}>
      {/* 모달을 열기 위한 버튼 */}
      <DialogTrigger asChild>
        <Button variant="default" size="sm">
          Add Vendor Candidate
        </Button>
      </DialogTrigger>

      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>Create New Vendor Candidate</DialogTitle>
          <DialogDescription>
            새 Vendor Candidate 정보를 입력하고 <b>Create</b> 버튼을 누르세요.
          </DialogDescription>
        </DialogHeader>

        {/* shadcn/ui Form을 이용해 react-hook-form과 연결 */}
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)}>
            <div className="space-y-4 py-4">
              {/* Company Name 필드 */}
              <FormField
                control={form.control}
                name="companyName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="after:content-['*'] after:ml-0.5 after:text-red-500">
                      Company Name
                    </FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Enter company name"
                        {...field}
                        disabled={isSubmitting}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Contact Email 필드 */}
              <FormField
                control={form.control}
                name="contactEmail"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="after:content-['*'] after:ml-0.5 after:text-red-500">
                      Contact Email
                    </FormLabel>
                    <FormControl>
                      <Input
                        placeholder="email@example.com"
                        type="email"
                        {...field}
                        disabled={isSubmitting}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Contact Phone 필드 */}
              <FormField
                control={form.control}
                name="contactPhone"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Contact Phone</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="+82-10-1234-5678"
                        {...field}
                        disabled={isSubmitting}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Country 필드 */}
              <FormField
                control={form.control}
                name="country"
                render={({ field }) => {
                  const selectedCountry = countryArray.find(
                    (c) => c.code === field.value
                  )
                  return (
                    <FormItem>
                      <FormLabel>Country</FormLabel>
                      <Popover>
                        <PopoverTrigger asChild>
                          <FormControl>
                            <Button
                              variant="outline"
                              role="combobox"
                              className={cn(
                                "w-full justify-between",
                                !field.value && "text-muted-foreground"
                              )}
                              disabled={isSubmitting}
                            >
                              {selectedCountry
                                ? selectedCountry.label
                                : "Select a country"}
                              <ChevronsUpDown className="ml-2 h-4 w-4 opacity-50" />
                            </Button>
                          </FormControl>
                        </PopoverTrigger>
                        <PopoverContent className="w-[300px] p-0">
                          <Command>
                            <CommandInput placeholder="Search country..." />
                            <CommandList>
                              <CommandEmpty>No country found.</CommandEmpty>
                              <CommandGroup className="max-h-[300px] overflow-y-auto">
                                {countryArray.map((country) => (
                                  <CommandItem
                                    key={country.code}
                                    value={country.label}
                                    onSelect={() =>
                                      field.onChange(country.code)
                                    }
                                  >
                                    <Check
                                      className={cn(
                                        "mr-2 h-4 w-4",
                                        country.code === field.value
                                          ? "opacity-100"
                                          : "opacity-0"
                                      )}
                                    />
                                    {country.label}
                                  </CommandItem>
                                ))}
                              </CommandGroup>
                            </CommandList>
                          </Command>
                        </PopoverContent>
                      </Popover>
                      <FormMessage />
                    </FormItem>
                  )
                }}
              />

              {/* Source 필드 */}
              <FormField
                control={form.control}
                name="source"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Source</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Where this candidate was found"
                        {...field}
                        disabled={isSubmitting}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Status 필드 */}
              {/* <FormField
                control={form.control}
                name="status"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Status</FormLabel>
                    <Select
                      onValueChange={field.onChange}
                      defaultValue={field.value}
                      disabled={isSubmitting}
                    >
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="Select status" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectGroup>
                          {vendorCandidates.status.enumValues.map((status) => (
                            <SelectItem key={status} value={status}>
                              {status}
                            </SelectItem>
                          ))}
                        </SelectGroup>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              /> */}
            </div>

            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => setOpen(false)}
                disabled={isSubmitting}
              >
                Cancel
              </Button>
              <Button type="submit" disabled={isSubmitting}>
                {isSubmitting ? "Creating..." : "Create"}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}