"use client";

import { useState, useCallback, useMemo } from "react";
import { DataTable } from "@/components/ui/data-table";
import { ShipmentsOverview } from "./columns";
import { EntityDetailSheet } from "@/components/dashboard/data-view/EntityDetailSheet";
import { ShipmentEditForm } from "./ShipmentEditForm";
import { ShipmentCreateForm } from "./ShipmentCreateForm";
import { deleteShipment } from "@/actions/sales";
import { toast } from "sonner";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";

interface ShipmentTrackingTableProps {
  columns: any[];
  data: any[];
  creating: boolean;
  onCreatingChange: (creating: boolean) => void;
}

export function ShipmentTrackingTable({ columns, data, creating, onCreatingChange }: ShipmentTrackingTableProps) {
  const [selectedShipment, setSelectedShipment] = useState<ShipmentsOverview | null>(null);
  const [editingShipment, setEditingShipment] = useState<ShipmentsOverview | null>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [shipmentToDelete, setShipmentToDelete] = useState<ShipmentsOverview | null>(null);

  const handleEdit = useCallback((shipment: ShipmentsOverview) => {
    setEditingShipment(shipment);
  }, []);

  const handleDelete = useCallback((shipment: ShipmentsOverview) => {
    setShipmentToDelete(shipment);
    setDeleteDialogOpen(true);
  }, []);

  const confirmDelete = async () => {
    if (!shipmentToDelete) return;

    try {
      const response = await deleteShipment({ id: shipmentToDelete.id });
      if ("error" in response) {
        toast.error(response.error);
      } else {
        toast.success(response.message || "Sendung erfolgreich gelöscht");
      }
    } catch (error) {
      toast.error("Ein unerwarteter Fehler ist aufgetreten");
    }
    setDeleteDialogOpen(false);
    setShipmentToDelete(null);
  };

  const tableColumns = useMemo(() => columns.map((col) => ({
    ...col,
    meta: {
      onEdit: handleEdit,
      onDelete: handleDelete,
    },
  })), [columns, handleEdit, handleDelete]);

  const handleRowClick = useCallback((row: ShipmentsOverview) => setSelectedShipment(row), []);

  return (
    <>
      <DataTable
        columns={tableColumns}
        data={data}
        onRowClick={handleRowClick}
      />
      <EntityDetailSheet
        type="shipment"
        data={selectedShipment}
        open={!!selectedShipment}
        onOpenChange={(open) => !open && setSelectedShipment(null)}
      />
      {editingShipment && (
        <ShipmentEditForm
          shipment={editingShipment}
          open={!!editingShipment}
          onOpenChange={(open) => !open && setEditingShipment(null)}
        />
      )}
      {creating && (
        <ShipmentCreateForm
          open={creating}
          onOpenChange={onCreatingChange}
        />
      )}
      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Sendung löschen</AlertDialogTitle>
            <AlertDialogDescription>
              Sind Sie sicher, dass Sie die Sendung &quot;{shipmentToDelete?.trackingNumber}&quot; löschen möchten? Diese Aktion kann nicht rückgängig gemacht werden.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Abbrechen</AlertDialogCancel>
            <AlertDialogAction onClick={confirmDelete}>Löschen</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}