"use client"

import * as React from "react"
import { useForm, useWatch } 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 { createTagSchema, type CreateTagSchema } from "@/lib/tags/validations"
import { createTag } from "@/lib/tags/service"
import { toast } from "sonner"
import { Loader2 } from "lucide-react"
import { cn } from "@/lib/utils"
import { useRouter } from "next/navigation"

// Popover + Command
import {
  Popover,
  PopoverTrigger,
  PopoverContent,
} from "@/components/ui/popover"
import {
  Command,
  CommandInput,
  CommandList,
  CommandGroup,
  CommandItem,
  CommandEmpty,
} from "@/components/ui/command"
import { ChevronsUpDown, Check } from "lucide-react"

// The dynamic Tag Type definitions
import { tagTypeDefinitions } from "./tag-type-definitions"

// Add Select component for dropdown fields
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { ScrollArea } from "@/components/ui/scroll-area"

interface AddTagDialogProps {
  selectedPackageId: number | null
}

export function AddTagDialog({ selectedPackageId }: AddTagDialogProps) {
  const [open, setOpen] = React.useState(false)
  const [isPending, startTransition] = React.useTransition()
  const router = useRouter()

  const form = useForm<CreateTagSchema>({
    resolver: zodResolver(createTagSchema),
    defaultValues: {
      tagType: "",       // user picks 
      tagNo: "",         // auto-generated 
      description: "",
      functionCode: "",
      seqNumber: "",
      valveAcronym: "",
      processUnit: "",
    },
  })

  const watchAll = useWatch({ control: form.control })

  // 1) Find the selected tag type definition
  const currentTagTypeDef = React.useMemo(() => {
    return tagTypeDefinitions.find((def) => def.id === watchAll.tagType) || null
  }, [watchAll.tagType])

  // 2) Whenever the user changes sub-fields, re-generate `tagNo`
  React.useEffect(() => {
    if (!currentTagTypeDef) {
      // if no type selected, no auto-generation
      return
    }
    
    // Prevent infinite loop by excluding tagNo from the watched dependencies
    // This is crucial because setting tagNo would trigger another update
    const { tagNo, ...fieldsToWatch } = watchAll
    
    const newTagNo = currentTagTypeDef.generateTagNo(fieldsToWatch as CreateTagSchema)
    
    // Only update if different to avoid unnecessary re-renders
    if (form.getValues("tagNo") !== newTagNo) {
      form.setValue("tagNo", newTagNo, { shouldValidate: false })
    }
  }, [currentTagTypeDef, watchAll, form])

  // Check if tag number is valid (doesn't contain '??' and is not empty)
  const isTagNoValid = React.useMemo(() => {
    const tagNo = form.getValues("tagNo");
    return tagNo && tagNo.trim() !== "" && !tagNo.includes("??");
  }, [form, watchAll.tagNo]);

  // onSubmit
  async function onSubmit(data: CreateTagSchema) {
    startTransition(async () => {
      if (!selectedPackageId) {
        toast.error("No selectedPackageId.")
        return
      }

      const result = await createTag(data, selectedPackageId)
      if ("error" in result) {
        toast.error(`Error: ${result.error}`)
        return
      }

      toast.success("Tag created successfully!")
      form.reset()
      setOpen(false)
      router.refresh()

    })
  }

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

  // 3) TagType selection UI (like your Command menu)
  function renderTagTypeSelector(field: any) {
    const [popoverOpen, setPopoverOpen] = React.useState(false)
    return (
      <FormItem>
        <FormLabel>Tag Type</FormLabel>
        <FormControl>
          <Popover open={popoverOpen} onOpenChange={setPopoverOpen}>
            <PopoverTrigger asChild>
              <Button
                variant="outline"
                role="combobox"
                aria-expanded={popoverOpen}
                className="w-full justify-between"
              >
                {field.value
                  ? tagTypeDefinitions.find((d) => d.id === field.value)?.label
                  : "Select Tag Type..."}
                <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-full p-0">
              <Command>
                <CommandInput placeholder="Search Tag Type..." />
                <CommandList>
                  <CommandEmpty>No tag type found.</CommandEmpty>
                  <CommandGroup>
                    {tagTypeDefinitions.map((def,index) => (
                      <CommandItem
                        key={index}
                        onSelect={() => {
                          field.onChange(def.id) // store the 'id'
                          setPopoverOpen(false)
                        }}
                        value={def.id}
                      >
                        {def.label}
                        <Check
                          className={cn(
                            "ml-auto h-4 w-4",
                            field.value === def.id
                              ? "opacity-100"
                              : "opacity-0"
                          )}
                        />
                      </CommandItem>
                    ))}
                  </CommandGroup>
                </CommandList>
              </Command>
            </PopoverContent>
          </Popover>
        </FormControl>
        <FormMessage />
      </FormItem>
    )
  }

  // 4) Render sub-fields based on currentTagTypeDef
  // Updated to handle different field types (text, select)
  function renderSubFields() {
    if (!currentTagTypeDef) return null
    
    return currentTagTypeDef.subFields.map((subField, index) => (
      
      <FormField
        key={`${subField.name}-${index}`}
        control={form.control}
        name={subField.name as keyof CreateTagSchema}
        render={({ field }) => (
          <FormItem>
            <FormLabel>{subField.label}</FormLabel>
            <FormControl>
              {subField.type === "select" && subField.options ? (
                <Select
                  value={field.value || ""}
                  onValueChange={field.onChange}
                >
                  <SelectTrigger className="w-full">
                    <SelectValue placeholder={subField.placeholder || "Select an option"} />
                  </SelectTrigger>
                  <SelectContent>
                    {subField.options.map((option, index) => (
                      <SelectItem key={index} value={option.value}>
                        {option.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              ) : (
                <Input
                  placeholder={subField.placeholder || ""}
                  value={field.value || ""}
                  onChange={field.onChange}
                  onBlur={field.onBlur}
                  name={field.name}
                  ref={field.ref}
                />
              )}
            </FormControl>
            {subField.formatHint && (
              <p className="text-sm text-muted-foreground mt-1">
                {subField.formatHint}
              </p>
            )}
            <FormMessage />
          </FormItem>
        )}
      />
    ))
  }

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

      <DialogContent className="max-w-md max-h-[90vh] overflow-y-auto">
      <DialogHeader>
          <DialogTitle>Add New Tag</DialogTitle>
          <DialogDescription>
            Select a Tag Type and fill in sub-fields. The Tag No will be generated automatically.
          </DialogDescription>
        </DialogHeader>
        <ScrollArea className="flex-1">

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <div className="space-y-4">
              {/* Tag Type - Outside ScrollArea as it's always visible */}
              <FormField
                control={form.control}
                name="tagType"
                render={({ field }) => renderTagTypeSelector(field)}
              />
            </div>

            {/* ScrollArea for dynamic fields */}
            <ScrollArea className="h-[50vh] pr-4">
              <div className="space-y-4">
                {/* sub-fields from the selected tagType */}
                {renderSubFields()}

                {/* Tag No (auto-generated) */}
                <FormField
                  control={form.control}
                  name="tagNo"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Tag No (auto-generated)</FormLabel>
                      <FormControl>
                        <Input
                          placeholder="Auto-generated..."
                          {...field}
                          readOnly
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                {/* Description (optional) */}
                <FormField
                  control={form.control}
                  name="description"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Description </FormLabel>
                      <FormControl>
                        <Input
                          placeholder="Optional desc..."
                          value={field.value ?? ""}
                          onChange={(e) => field.onChange(e.target.value)}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </ScrollArea>
            </form>
        </Form>
        </ScrollArea>

            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => {
                  form.reset();
                  setOpen(false);
                }}
                disabled={isPending}
              >
                Cancel
              </Button>
              <Button type="submit" disabled={isPending || !isTagNoValid}>
                {isPending && (
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                )}
                Create
              </Button>
            </DialogFooter>


      </DialogContent>
    </Dialog>
  )
}