import { Button } from '@repo/shadcn/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@repo/shadcn/components/ui/dialog';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@repo/shadcn/components/ui/table';
import { Input } from '@repo/shadcn/input';
import { Label } from '@repo/shadcn/label';
import { Trash2 } from 'lucide-react';
import { useState } from 'react';
import { useFieldArray, useFormContext } from 'react-hook-form';

export function EquipmentList() {
  const { control, register } = useFormContext();
  const { fields, append, remove } = useFieldArray({
    control,
    name: 'equipmentList',
  });
  const [isOpen, setIsOpen] = useState(false);
  const [newItem, setNewItem] = useState({
    machine: '',
    specifications: '',
    quantity: '',
  });

  const handleAdd = () => {
    if (newItem.machine && newItem.quantity) {
      append({ ...newItem, quantity: Number(newItem.quantity) });
      setNewItem({ machine: '', specifications: '', quantity: '' });
      setIsOpen(false);
    }
  };

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <h3 className="text-lg font-medium">Datos del Equipamiento</h3>
        <Dialog open={isOpen} onOpenChange={setIsOpen}>
          <DialogTrigger asChild>
            <Button variant="outline">Agregar Maquinaria</Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Agregar Maquinaria/Equipo</DialogTitle>
            </DialogHeader>
            <DialogDescription className="sr-only">
              Datos de equipamiento
            </DialogDescription>
            <div className="space-y-4 py-4">
              <div className="space-y-2">
                <Label>Maquinaria</Label>
                <Input
                  value={newItem.machine}
                  onChange={(e) =>
                    setNewItem({ ...newItem, machine: e.target.value })
                  }
                  placeholder="Nombre de la maquinaria"
                />
              </div>
              <div className="space-y-2">
                <Label>Especificaciones</Label>
                <Input
                  value={newItem.specifications}
                  onChange={(e) =>
                    setNewItem({ ...newItem, specifications: e.target.value })
                  }
                  placeholder="Especificaciones técnicas"
                />
              </div>
              <div className="space-y-2">
                <Label>Cantidad</Label>
                <Input
                  type="number"
                  value={newItem.quantity}
                  onChange={(e) =>
                    setNewItem({ ...newItem, quantity: e.target.value })
                  }
                  placeholder="0"
                />
              </div>
              <div className="flex justify-end gap-4">
                <Button
                  variant="outline"
                  type="button"
                  onClick={() => setIsOpen(false)}
                >
                  Cancelar
                </Button>

                <Button onClick={handleAdd}>Guardar</Button>
              </div>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      <div className="border rounded-md">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Maquinaria</TableHead>
              <TableHead>Especificaciones</TableHead>
              <TableHead>Cantidad</TableHead>
              <TableHead className="w-[50px]"></TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {fields.map((field, index) => (
              <TableRow key={field.id}>
                <TableCell>
                  <input
                    type="hidden"
                    {...register(`equipmentList.${index}.machine`)}
                  />
                  {/* @ts-ignore */}
                  {field.machine}
                </TableCell>
                <TableCell>
                  <input
                    type="hidden"
                    {...register(`equipmentList.${index}.specifications`)}
                  />
                  {/* @ts-ignore */}
                  {field.specifications}
                </TableCell>
                <TableCell>
                  <input
                    type="hidden"
                    {...register(`equipmentList.${index}.quantity`)}
                  />
                  {/* @ts-ignore */}
                  {field.quantity}
                </TableCell>
                <TableCell>
                  <Button
                    variant="ghost"
                    size="icon"
                    onClick={() => remove(index)}
                  >
                    <Trash2 className="h-4 w-4 text-destructive" />
                  </Button>
                </TableCell>
              </TableRow>
            ))}
            {fields.length === 0 && (
              <TableRow>
                <TableCell
                  colSpan={4}
                  className="text-center text-muted-foreground"
                >
                  No hay equipamiento registrado
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}
