"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { createLayoutSectionField } from "@/app/actions/layout-configurations";

interface AddFieldDialogProps {
  sectionId: number;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSuccess: () => void;
}

export function AddFieldDialog({
  sectionId,
  open,
  onOpenChange,
  onSuccess,
}: AddFieldDialogProps) {
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    name: "",
    dataType: "STRING",
    dataTypeFormat: "",
    cellPosition: "",
    importTableColumnName: "",
    importColumnOrderNumber: 0,
  });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);

    try {
      const result = await createLayoutSectionField(sectionId, {
        ...formData,
        importColumnOrderNumber: parseInt(formData.importColumnOrderNumber.toString()),
      });

      if (result.success) {
        onSuccess();
        setFormData({
          name: "",
          dataType: "STRING",
          dataTypeFormat: "",
          cellPosition: "",
          importTableColumnName: "",
          importColumnOrderNumber: 0,
        });
      }
    } catch (error) {
      console.error("Error adding field:", error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>Add New Field</DialogTitle>
          <DialogDescription>
            Add a new field to this section configuration.
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit}>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <Label htmlFor="name">Field Name</Label>
              <Input
                id="name"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                required
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="dataType">Data Type</Label>
              <Select
                value={formData.dataType}
                onValueChange={(value) => setFormData({ ...formData, dataType: value })}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="STRING">String</SelectItem>
                  <SelectItem value="NUMBER">Number</SelectItem>
                  <SelectItem value="DATE">Date</SelectItem>
                  <SelectItem value="BOOLEAN">Boolean</SelectItem>
                  <SelectItem value="EMAIL">Email</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="dataTypeFormat">Data Type Format</Label>
              <Input
                id="dataTypeFormat"
                value={formData.dataTypeFormat}
                onChange={(e) => setFormData({ ...formData, dataTypeFormat: e.target.value })}
                placeholder="e.g., YYYY-MM-DD"
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="cellPosition">Cell Position</Label>
              <Input
                id="cellPosition"
                value={formData.cellPosition}
                onChange={(e) => setFormData({ ...formData, cellPosition: e.target.value })}
                required
                placeholder="e.g., A1"
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="importTableColumnName">Import Column Name</Label>
              <Input
                id="importTableColumnName"
                value={formData.importTableColumnName}
                onChange={(e) => setFormData({ ...formData, importTableColumnName: e.target.value })}
                required
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="importColumnOrderNumber">Column Order</Label>
              <Input
                id="importColumnOrderNumber"
                type="number"
                value={formData.importColumnOrderNumber}
                onChange={(e) => setFormData({ ...formData, importColumnOrderNumber: parseInt(e.target.value) || 0 })}
                required
                min={0}
              />
            </div>
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
              Cancel
            </Button>
            <Button type="submit" disabled={loading}>
              {loading ? "Adding..." : "Add Field"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}