'use client';

import { useMemo, useState } from 'react';
import { useMutation, useSuspenseQuery } from '@tanstack/react-query';
import type { ColumnDef } from '@tanstack/react-table';
import { parseAsInteger, parseAsString, useQueryStates } from 'nuqs';
import { toast } from 'sonner';
import { AlertModal } from '@/components/modal/alert-modal';
import { Icons } from '@/components/icons';
import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger
} from '@/components/ui/dropdown-menu';
import { DataTable } from '@/components/ui/table/data-table';
import { DataTableToolbar } from '@/components/ui/table/data-table-toolbar';
import { useDataTable } from '@/hooks/use-data-table';
import { getSortingStateParser } from '@/lib/parsers';
import {
  createMasterOptionMutation,
  deleteMasterOptionMutation,
  updateMasterOptionMutation
} from '../api/mutations';
import { masterOptionsQueryOptions } from '../api/queries';
import type { MasterOptionItem, MasterOptionMutationPayload } from '../api/types';
import { columns } from './columns';
import { MasterOptionsFormDialog } from './master-options-form-dialog';

const columnIds = columns.map((column) => column.id).filter(Boolean) as string[];

export function MasterOptionsTable() {
  const [params] = useQueryStates({
    page: parseAsInteger.withDefault(1),
    perPage: parseAsInteger.withDefault(10),
    name: parseAsString,
    category: parseAsString,
    sort: getSortingStateParser(columnIds).withDefault([])
  });
  const [editingOption, setEditingOption] = useState<MasterOptionItem | undefined>();
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState<MasterOptionItem | null>(null);

  const filters = {
    page: params.page,
    limit: params.perPage,
    ...(params.name && { search: params.name }),
    ...(params.category && { category: params.category }),
    ...(params.sort.length > 0 && { sort: JSON.stringify(params.sort) })
  };
  const { data } = useSuspenseQuery(masterOptionsQueryOptions(filters));

  const createMutation = useMutation({
    ...createMasterOptionMutation,
    onSuccess: () => {
      toast.success('Master option created.');
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : 'Create failed');
    }
  });
  const updateMutation = useMutation({
    ...updateMasterOptionMutation,
    onSuccess: () => {
      toast.success('Master option updated.');
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : 'Update failed');
    }
  });
  const deleteMutation = useMutation({
    ...deleteMasterOptionMutation,
    onSuccess: () => {
      toast.success('Master option deleted.');
      setDeleteTarget(null);
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : 'Delete failed');
    }
  });

  const tableColumns = useMemo<ColumnDef<MasterOptionItem>[]>(
    () => [
      ...columns,
      {
        id: 'actions',
        cell: ({ row }) => (
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant='ghost' size='icon' className='h-8 w-8'>
                <Icons.moreHorizontal className='h-4 w-4' />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align='end'>
              <DropdownMenuItem
                onClick={() => {
                  setEditingOption(row.original);
                  setIsFormOpen(true);
                }}
              >
                Edit
              </DropdownMenuItem>
              <DropdownMenuItem
                className='text-destructive'
                onClick={() => setDeleteTarget(row.original)}
              >
                Soft delete
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        )
      }
    ],
    []
  );

  const pageCount = Math.ceil(data.total_items / params.perPage);
  const { table } = useDataTable({
    data: data.items,
    columns: tableColumns,
    pageCount,
    shallow: true,
    debounceMs: 500
  });

  async function handleSubmit(values: MasterOptionMutationPayload) {
    if (editingOption) {
      await updateMutation.mutateAsync({
        id: editingOption.id,
        values
      });
      return;
    }

    await createMutation.mutateAsync(values);
  }

  return (
    <DataTable table={table}>
      <DataTableToolbar table={table} />
      <MasterOptionsFormDialog
        open={isFormOpen}
        onOpenChange={setIsFormOpen}
        onSubmit={handleSubmit}
        pending={createMutation.isPending || updateMutation.isPending}
        option={editingOption}
        availableParents={data.items}
      />
      <AlertModal
        isOpen={Boolean(deleteTarget)}
        onClose={() => setDeleteTarget(null)}
        onConfirm={() => {
          if (deleteTarget) {
            deleteMutation.mutate(deleteTarget.id);
          }
        }}
        loading={deleteMutation.isPending}
      />
    </DataTable>
  );
}
