import React, { useEffect, useState } from 'react';
import { Trash2 } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import {
  useFieldArray,
  Controller,
  Control,
  FieldValues,
  FieldArrayPath,
  Path,
  FieldArray,
  ArrayPath,
} from 'react-hook-form';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
} from '@/components/ui/command';
import { MENU_PLATFORMS, YES_NO } from '@/constants';

// ---------------------- Types ----------------------
export interface MenuActionItem {
  active: number;
  title: string;
  action: string;
  is_visible: number;
  platform: number;
}

// Define a proper form data type that includes the field array
export interface FormDataWithMenuActions extends FieldValues {
  items: MenuActionItem[];
}

export interface MenuActionItemsProps<
  TFieldValues extends FormDataWithMenuActions,
> {
  control: Control<TFieldValues>;
  name?: FieldArrayPath<TFieldValues>;
  record?: {
    actions?: MenuActionItem[];
    [key: string]: unknown;
  };
}

// ------------------- Default Item -------------------
const defaultItem: MenuActionItem = {
  active: 1,
  title: '',
  action: '',
  is_visible: 1,
  platform: 1,
};

// ------------------- Component -------------------
export default function MenuActionItems<
  TFieldValues extends FormDataWithMenuActions,
>({
  control,
  name = 'items' as FieldArrayPath<TFieldValues>,
  record,
}: MenuActionItemsProps<TFieldValues>) {
  const [initialized, setInitialized] = useState(false);
  const { fields, append, remove, replace } = useFieldArray({
    control,
    name,
  });

  type FieldArrayItem = FieldArray<TFieldValues, ArrayPath<TFieldValues>>;

  const [openPopover, setOpenPopover] = useState<{
    isVisibleIndex: number | null;
    platformIndex: number | null;
  }>({ isVisibleIndex: null, platformIndex: null });

  // Initialize fields on first load
  useEffect(() => {
    if (
      !initialized &&
      Array.isArray(record?.actions) &&
      record.actions.length > 0
    ) {
      const fieldArrayData = record.actions.map((r) => ({
        active: r.active ?? 1,
        title: r.title ?? '',
        action: r.action ?? '',
        is_visible: r.is_visible ?? 1,
        platform: r.platform ?? 1,
      }));

      replace(fieldArrayData as FieldArrayItem[]);
      setInitialized(true);
    }

    if (!initialized && fields.length === 0 && !record?.actions?.length) {
      append(defaultItem as FieldArrayItem);
      setInitialized(true);
    }
  }, [record, initialized, replace, append, fields.length]);

  return (
    <div className="space-y-2 p-1 ml-4 mr-4">
      <h4 className="text-xl font-semibold">Menu Actions</h4>

      {fields.map((fieldItem, index) => (
        <Card key={fieldItem.id} className="space-y-1 pt-4 pb-4 pl-0 pr-0 mt-4">
          <CardContent className="flex flex-row items-end gap-4">
            {/* Active */}
            <div className="w-[6%] flex items-center gap-2 mb-2">
              <Controller
                name={`${name}.${index}.active` as Path<TFieldValues>}
                control={control}
                render={({ field }) => (
                  <Checkbox
                    id={`active-${index}`}
                    checked={field.value === 1}
                    onCheckedChange={(checked) =>
                      field.onChange(checked ? 1 : 0)
                    }
                  />
                )}
              />
              <label
                htmlFor={`active-${index}`}
                className="text-sm font-bold mb-0"
              >
                Active
              </label>
            </div>

            {/* Title */}
            <div className="w-[35%]">
              <Controller
                name={`${name}.${index}.title` as Path<TFieldValues>}
                control={control}
                render={({ field }) => <Input {...field} placeholder="Title" />}
              />
            </div>

            {/* Action */}
            <div className="w-[35%]">
              <Controller
                name={`${name}.${index}.action` as Path<TFieldValues>}
                control={control}
                render={({ field }) => (
                  <Input {...field} placeholder="Action" />
                )}
              />
            </div>

            {/* Is Visible */}
            <div className="w-[18%]">
              <Controller
                name={`${name}.${index}.is_visible` as Path<TFieldValues>}
                control={control}
                render={({ field }) => (
                  <Popover
                    open={openPopover.isVisibleIndex === index}
                    onOpenChange={(open) =>
                      setOpenPopover((prev) => ({
                        ...prev,
                        isVisibleIndex: open ? index : null,
                      }))
                    }
                  >
                    <PopoverTrigger asChild>
                      <Button
                        className="w-full text-left flex justify-between"
                        variant="outline"
                      >
                        {YES_NO.find((o) => o.id === field.value)?.name ||
                          'Choose Option'}
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="p-0 z-[9999]">
                      <Command>
                        <CommandInput
                          placeholder="Search options..."
                          className="h-9"
                        />
                        <CommandEmpty>No options found</CommandEmpty>
                        <CommandGroup>
                          {YES_NO.map((option) => (
                            <CommandItem
                              key={option.id}
                              onSelect={() => field.onChange(option.id)}
                              aria-selected={
                                String(option.id) === String(field.value)
                              }
                            >
                              {option.name}
                            </CommandItem>
                          ))}
                        </CommandGroup>
                      </Command>
                    </PopoverContent>
                  </Popover>
                )}
              />
            </div>

            {/* Platform */}
            <div className="w-[18%]">
              <Controller
                name={`${name}.${index}.platform` as Path<TFieldValues>}
                control={control}
                render={({ field }) => (
                  <Popover
                    open={openPopover.platformIndex === index}
                    onOpenChange={(open) =>
                      setOpenPopover((prev) => ({
                        ...prev,
                        platformIndex: open ? index : null,
                      }))
                    }
                  >
                    <PopoverTrigger asChild>
                      <Button
                        className="w-full text-left flex justify-between"
                        variant="outline"
                      >
                        {MENU_PLATFORMS.find((o) => o.id === field.value)
                          ?.name || 'Choose Option'}
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="p-0 z-[9999]">
                      <Command>
                        <CommandInput
                          placeholder="Search options..."
                          className="h-9"
                        />
                        <CommandEmpty>No options found</CommandEmpty>
                        <CommandGroup>
                          {MENU_PLATFORMS.map((option) => (
                            <CommandItem
                              key={option.id}
                              onSelect={() => field.onChange(option.id)}
                              aria-selected={
                                String(option.id) === String(field.value)
                              }
                            >
                              {option.name}
                            </CommandItem>
                          ))}
                        </CommandGroup>
                      </Command>
                    </PopoverContent>
                  </Popover>
                )}
              />
            </div>

            {/* Remove */}
            <div className="w-[6%] flex justify-end">
              <Button
                size="icon"
                variant="destructive"
                onClick={() => remove(index)}
              >
                <Trash2 className="h-4 w-4" />
              </Button>
            </div>
          </CardContent>
        </Card>
      ))}

      <Button
        type="button"
        onClick={() => append(defaultItem as FieldArrayItem)}
      >
        + Add More
      </Button>
    </div>
  );
}
