import { ChevronDown, Trash2, Type } from 'lucide-react';

import { DatabaseViewFieldFilterAttributes } from '@colanode/core';
import { Button } from '@colanode/ui/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@colanode/ui/components/ui/dropdown-menu';
import { Input } from '@colanode/ui/components/ui/input';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@colanode/ui/components/ui/popover';
import { useDatabase } from '@colanode/ui/contexts/database';
import { useDatabaseView } from '@colanode/ui/contexts/database-view';
import { useViewFilter } from '@colanode/ui/hooks/use-view-filter';
import { nameFieldFilterOperators } from '@colanode/ui/lib/databases';

interface ViewNameFieldFilterProps {
  filter: DatabaseViewFieldFilterAttributes;
}

const isOperatorWithoutValue = (operator: string) => {
  return operator === 'is_empty' || operator === 'is_not_empty';
};

export const ViewNameFieldFilter = ({ filter }: ViewNameFieldFilterProps) => {
  const database = useDatabase();
  const view = useDatabaseView();
  const { updateFilter, removeFilter } = useViewFilter({
    viewId: view.id,
    filterId: filter.id,
  });

  const operator =
    nameFieldFilterOperators.find(
      (operator) => operator.value === filter.operator
    ) ?? nameFieldFilterOperators[0];

  if (!operator) {
    return null;
  }

  const textValue = filter.value as string | null;

  const hideInput = isOperatorWithoutValue(operator.value);

  return (
    <Popover
      open={view.isFieldFilterOpened(filter.id)}
      onOpenChange={() => {
        if (view.isFieldFilterOpened(filter.id)) {
          view.closeFieldFilter(filter.id);
        } else {
          view.openFieldFilter(filter.id);
        }
      }}
    >
      <PopoverTrigger asChild>
        <Button
          type="button"
          variant="outline"
          size="sm"
          className="text-muted-foregroundc border-dashed text-xs"
        >
          {database.nameField?.name ?? 'Name'}
        </Button>
      </PopoverTrigger>
      <PopoverContent className="flex w-96 flex-col gap-2 p-2">
        <div className="flex flex-row items-center gap-3 text-sm">
          <div className="flex flex-row items-center gap-0.5 p-1">
            <Type className="size-4" />
            <p>{database.nameField?.name ?? 'Name'}</p>
          </div>
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <div className="flex grow flex-row items-center gap-1 rounded-md p-1 font-semibold cursor-pointer hover:bg-accent">
                <p>{operator.label}</p>
                <ChevronDown className="size-4 text-muted-foreground" />
              </div>
            </DropdownMenuTrigger>
            <DropdownMenuContent>
              {nameFieldFilterOperators.map((operator) => (
                <DropdownMenuItem
                  key={operator.value}
                  onSelect={() => {
                    const value = isOperatorWithoutValue(operator.value)
                      ? null
                      : textValue;

                    updateFilter({
                      ...filter,
                      operator: operator.value,
                      value: value,
                    });
                  }}
                >
                  {operator.label}
                </DropdownMenuItem>
              ))}
            </DropdownMenuContent>
          </DropdownMenu>
          <Button variant="ghost" size="icon" onClick={removeFilter}>
            <Trash2 className="size-4" />
          </Button>
        </div>
        {!hideInput && (
          <Input
            value={textValue ?? ''}
            onChange={(e) => {
              const value = e.target.value;
              updateFilter({
                ...filter,
                value: value,
              });
            }}
          />
        )}
      </PopoverContent>
    </Popover>
  );
};
