import * as React from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
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 {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Check, ChevronsUpDown, Loader } from "lucide-react"
import { cn } from "@/lib/utils"
import { toast } from "sonner"

import { createRoleSchema, type CreateRoleSchema } from "../validations"
import { createRole } from "../services"
import { Textarea } from "@/components/ui/textarea"
import { Company } from "@/db/schema/companies"
import { getAllCompanies } from "@/lib/admin-users/service"
import {
  Popover,
  PopoverTrigger,
  PopoverContent,
} from "@/components/ui/popover"
import {
  Command,
  CommandInput,
  CommandList,
  CommandGroup,
  CommandItem,
  CommandEmpty,
} from "@/components/ui/command"



const domainOptions = [
  { value: "partners", label: "협력업체" },
  { value: "evcp", label: "삼성중공업" },
]

export function AddRoleDialog() {
  const [open, setOpen] = React.useState(false)
  const [isAddPending, startAddTransition] = React.useTransition()
  const [companies, setCompanies] = React.useState<Company[]>([])  // 회사 목록

  React.useEffect(() => {
    getAllCompanies().then((res) => {
      setCompanies(res)
    })
  }, [])

  // react-hook-form 세팅
  const form = useForm<CreateRoleSchema>({
    resolver: zodResolver(createRoleSchema),
    defaultValues: {
      name: "",
      domain: "evcp",     // 기본값
      description: "",
      // companyId: null,  // optional
    },
  })

  async function onSubmit(data: CreateRoleSchema) {
    startAddTransition(async () => {
      const result = await createRole(data)
      if (result.error) {
        toast.error(`에러: ${result.error}`)
        return
      }
      form.reset()
      setOpen(false)
      toast.success("Role added")
    })
  }

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

  // domain이 partners일 경우 companyId 입력 필드 보이게
  const selectedDomain = form.watch("domain")

  return (
    <Dialog open={open} onOpenChange={handleDialogOpenChange}>
      <DialogTrigger asChild>
        <Button variant="default" size="sm">
          Add Role
        </Button>
      </DialogTrigger>

      <DialogContent>
        <DialogHeader>
          <DialogTitle>Create New Role</DialogTitle>
          <DialogDescription>
            새 Role 정보를 입력하고 <b>Create</b> 버튼을 누르세요.
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)}>
            <div className="space-y-4 py-4">
              {/* 1) Role Name */}
              <FormField
                control={form.control}
                name="name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Role Name</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="e.g. admin"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 2) Description */}
              <FormField
                control={form.control}
                name="description"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Role Description</FormLabel>
                    <FormControl>
                      <Textarea
                        placeholder="Describe role"
                        className="resize-none"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 3) Domain Select */}
              <FormField
                control={form.control}
                name="domain"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Domain</FormLabel>
                    <FormControl>
                      <Select
                        // domain이 바뀔 때마다 form state에도 반영
                        onValueChange={field.onChange}
                        value={field.value}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Select Domain" />
                        </SelectTrigger>
                        <SelectContent>
                          {domainOptions.map((v, index) => (
                            <SelectItem key={index} value={v.value}>
                              {v.label}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 4) companyId => domain이 partners인 경우만 노출 */}
              {selectedDomain === "partners" && (
              <FormField
              control={form.control}
              name="companyId"
              render={({ field }) => {
                // 현재 선택된 회사 ID (number) → 문자열
                const valueString = field.value ? String(field.value) : ""


                // 현재 선택된 회사
                const selectedCompany = companies.find(
                  (c) => String(c.id) === valueString
                )

                const selectedCompanyLabel = selectedCompany && `${selectedCompany.name} ${selectedCompany.taxID}`

                const [popoverOpen, setPopoverOpen] = React.useState(false)


                return (
                  <FormItem>
                    <FormLabel>Company</FormLabel>
                    <FormControl>
                      <Popover
                        open={popoverOpen}
                        onOpenChange={setPopoverOpen}
                        modal={true}
                      >
                        <PopoverTrigger asChild>
                          <Button
                            variant="outline"
                            role="combobox"
                            aria-expanded={popoverOpen}
                            className="w-full justify-between"
                          >
                            {selectedCompany
                              ? `${selectedCompany.name} ${selectedCompany.taxID}`
                              : "Select company..."}
                            <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                          </Button>
                        </PopoverTrigger>

                        <PopoverContent className="w-full p-0">
                          <Command>
                            <CommandInput
                              placeholder="Search company..."
                              className="h-9"

                            />
                            <CommandList>
                              <CommandEmpty>No company found.</CommandEmpty>
                              <CommandGroup>
                                {companies.map((comp) => {
                                  // string(comp.id)
                                  const compIdStr = String(comp.id)
                                  const label = `${comp.name}${comp.taxID}`
                                  const label2 = `${comp.name} ${comp.taxID}`
                                  return (
                                    <CommandItem
                                      key={comp.id}
                                      value={label2}
                                      onSelect={() => {
                                        // 회사 ID를 number로
                                        field.onChange(Number(comp.id))
                                        setPopoverOpen(false)

                                      }}
                                    >
                                      {label2}
                                      <Check
                                        className={cn(
                                          "ml-auto h-4 w-4",
                                          selectedCompanyLabel === label2
                                            ? "opacity-100"
                                            : "opacity-0"
                                        )}
                                      />
                                    </CommandItem>
                                  )
                                })}
                              </CommandGroup>
                            </CommandList>
                          </Command>
                        </PopoverContent>
                      </Popover>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )
              }}
            />
              )}
            </div>

            {/* Footer */}
            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => setOpen(false)}
                disabled={isAddPending}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                disabled={form.formState.isSubmitting || isAddPending}
              >
                {isAddPending && (
                  <Loader
                    className="mr-2 size-4 animate-spin"
                    aria-hidden="true"
                  />
                )}
                Create
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}