"use client";

import { useState, useEffect } 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 { updateLayoutSectionField } from "@/app/actions/layout-configurations";

interface LayoutSectionField {
  id: number;
  name: string;
  dataType: string;
  dataTypeFormat: string | null;
  cellPosition: string;
  importTableColumnName: string;
  importColumnOrderNumber: number;
}

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

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

  useEffect(() => {
    if (field) {
      setFormData({
        name: field.name,
        dataType: field.dataType,
        dataTypeFormat: field.dataTypeFormat || "",
        cellPosition: field.cellPosition,
        importTableColumnName: field.importTableColumnName,
        importColumnOrderNumber: field.importColumnOrderNumber,
      });
    }
  }, [field]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!field) return;

    setLoading(true);

    try {
      const result = await updateLayoutSectionField(field.id, {
        name: formData.name,
        dataType: formData.dataType,
        dataTypeFormat: formData.dataTypeFormat || undefined,
        cellPosition: formData.cellPosition,
        importTableColumnName: formData.importTableColumnName,
        importColumnOrderNumber: parseInt(formData.importColumnOrderNumber.toString()),
      });

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

  if (!field) return null;

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

            <div className="grid gap-2">
              <Label htmlFor="edit-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="edit-dataTypeFormat">Data Type Format</Label>
              <Input
                id="edit-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="edit-cellPosition">Cell Position</Label>
              <Input
                id="edit-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="edit-importTableColumnName">Import Column Name</Label>
              <Input
                id="edit-importTableColumnName"
                value={formData.importTableColumnName}
                onChange={(e) => setFormData({ ...formData, importTableColumnName: e.target.value })}
                required
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="edit-importColumnOrderNumber">Column Order</Label>
              <Input
                id="edit-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 ? "Updating..." : "Update Field"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}