'use client';

import { useCallback, useState } from 'react';
import { Package as PackageIcon, Plus } from 'lucide-react';

import { PageHeader } from '@/components/page-header';
import { Button } from '@/components/ui/button';
import type { Package } from '@/types';

import { PackageDialog } from './components/PackageDialog';
import { PackageTable } from './components/PackageTable';
import { usePackageColumns } from './components/PackageColumns';
import { usePackageFilters } from './hooks/usePackageFilters';
import { usePackageForm } from './hooks/usePackageForm';
import {
  useDeletePackageMutation,
  usePackagesQuery,
  useProjectOptionsQuery,
} from './hooks/usePackageQueries';

export default function PackagePage() {
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const { skip, setSkip, limit, setLimit } = usePackageFilters();
  const packagesQuery = usePackagesQuery({ skip, limit });
  const projectsQuery = useProjectOptionsQuery();
  const deletePackageMutation = useDeletePackageMutation();
  const packageForm = usePackageForm({
    onSaved: () => setIsDialogOpen(false),
  });
  const {
    register,
    onSubmit,
    openCreate: prepareCreatePackage,
    openEdit: prepareEditPackage,
    resetForm,
    packageId,
    projectId,
    setProjectId,
    errors,
    isSubmitted,
    canSubmit,
    isSaving,
  } = packageForm;

  const openCreate = useCallback(() => {
    prepareCreatePackage();
    setIsDialogOpen(true);
  }, [prepareCreatePackage]);

  const openEdit = useCallback(
    (pkg: Package) => {
      prepareEditPackage(pkg);
      setIsDialogOpen(true);
    },
    [prepareEditPackage],
  );

  const handleDialogOpenChange = useCallback(
    (open: boolean) => {
      setIsDialogOpen(open);
      if (!open) {
        resetForm();
      }
    },
    [resetForm],
  );

  const deletePackage = useCallback(
    (pkg: Package) => {
      if (!confirm(`Are you sure you want to delete package "${pkg.name}"?`)) {
        return;
      }
      deletePackageMutation.mutate(pkg);
    },
    [deletePackageMutation],
  );

  const projects = projectsQuery.data?.items ?? [];
  const packages = packagesQuery.data?.items ?? [];
  const total = packagesQuery.data?.totalItems ?? 0;
  const columns = usePackageColumns(projects);

  return (
    <>
      <main className="relative z-10 space-y-5">
        <PageHeader
          title="Package Management"
          description="Manage project packages"
          icon={PackageIcon}
          actions={
            <Button onClick={openCreate} size="sm">
              <Plus />
              Add New Package
            </Button>
          }
        />

        <PackageTable
          columns={columns}
          packages={packages}
          isLoading={packagesQuery.isLoading || deletePackageMutation.isPending}
          skip={skip}
          limit={limit}
          total={total}
          onPageChange={setSkip}
          onLimitChange={setLimit}
          onEdit={openEdit}
          onDelete={deletePackage}
        />
      </main>

      <PackageDialog
        open={isDialogOpen}
        onOpenChange={handleDialogOpenChange}
        packageId={packageId}
        projectId={projectId}
        onProjectChange={setProjectId}
        register={register}
        errors={errors}
        isSubmitted={isSubmitted}
        onSubmit={onSubmit}
        canSubmit={canSubmit}
        isSaving={isSaving}
      />
    </>
  );
}
