"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { deleteLayoutSectionField } from "@/app/actions/layout-configurations";

interface LayoutSectionField {
  id: number;
  name: string;
  dataType: string;
  cellPosition: string;
}

interface DeleteFieldDialogProps {
  field: LayoutSectionField | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSuccess: () => void;
}

export function DeleteFieldDialog({
  field,
  open,
  onOpenChange,
  onSuccess,
}: DeleteFieldDialogProps) {
  const [loading, setLoading] = useState(false);

  const handleDelete = async () => {
    if (!field) return;

    setLoading(true);

    try {
      const result = await deleteLayoutSectionField(field.id);

      if (result.success) {
        onSuccess();
      }
    } catch (error) {
      console.error("Error deleting field:", error);
    } finally {
      setLoading(false);
    }
  };

  if (!field) return null;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Delete Field</DialogTitle>
          <DialogDescription>
            Are you sure you want to delete the field &quot;{field.name}&quot;? This action cannot be undone.
          </DialogDescription>
        </DialogHeader>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button variant="destructive" onClick={handleDelete} disabled={loading}>
            {loading ? "Deleting..." : "Delete Field"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}