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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@repo/shadcn/select';
import { Trash2 } from 'lucide-react';
import { useState } from 'react';
import { useFieldArray, useFormContext } from 'react-hook-form';
import { TrainingSchema } from '../schemas/training';

const UNIT_OPTIONS = ['KG', 'TON', 'UNID', 'LT', 'MTS', 'QQ', 'HM2', 'SACOS'];

export function ProductionList() {
  const { control, register } = useFormContext<TrainingSchema>();
  const { fields, append, remove } = useFieldArray({
    control,
    name: 'productionList',
  });
  const [isOpen, setIsOpen] = useState(false);
  const [newItem, setNewItem] = useState({
    supplyType: '',
    quantity: '',
    unit: '',
  });

  const handleAdd = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (newItem.supplyType && newItem.quantity && newItem.unit) {
      append({ ...newItem, quantity: Number(newItem.quantity) });
      setNewItem({ supplyType: '', quantity: '', unit: '' });
      setIsOpen(false);
    }
  };

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <h3 className="text-lg font-medium">Datos de Producción</h3>
        <Dialog open={isOpen} onOpenChange={setIsOpen}>
          <DialogTrigger asChild>
            <Button variant="outline">Agregar Producción</Button>
          </DialogTrigger>
          <DialogContent onPointerDownOutside={(e) => e.preventDefault()}>
            <DialogHeader>
              <DialogTitle>Materia prima requerida (mensual)</DialogTitle>
            </DialogHeader>
            <DialogDescription className="sr-only">
              Datos de producción
            </DialogDescription>
            <div className="space-y-4 py-4">
              <div className="space-y-2">
                <Label>Tipo de Insumo/Rubro</Label>
                <Input
                  value={newItem.supplyType}
                  onChange={(e) =>
                    setNewItem({ ...newItem, supplyType: e.target.value })
                  }
                  placeholder="Tipo"
                />
              </div>
              <div className="space-y-2">
                <Label>Cantidad Mensual</Label>
                <div className="flex gap-2">
                  <Input
                    type="number"
                    className="flex-1"
                    value={newItem.quantity}
                    onChange={(e) =>
                      setNewItem({ ...newItem, quantity: e.target.value })
                    }
                    placeholder="0"
                  />
                  <Select
                    value={newItem.unit}
                    onValueChange={(val) =>
                      setNewItem({ ...newItem, unit: val })
                    }
                  >
                    <SelectTrigger className="w-[120px]">
                      <SelectValue placeholder="Unidad" />
                    </SelectTrigger>
                    <SelectContent>
                      {UNIT_OPTIONS.map((unit) => (
                        <SelectItem key={unit} value={unit}>
                          {unit}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <div className="flex justify-end gap-4">
                <Button
                  variant="outline"
                  type="button"
                  onClick={(e) => {
                    e.preventDefault();
                    setIsOpen(false);
                  }}
                >
                  Cancelar
                </Button>

                <Button
                  type="button"
                  onClick={handleAdd}
                  disabled={
                    !newItem.supplyType || !newItem.quantity || !newItem.unit
                  }
                >
                  Guardar
                </Button>
              </div>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      <div className="border rounded-md">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Tipo Insumo</TableHead>
              <TableHead>Cantidad (Mensual)</TableHead>
              <TableHead className="w-[50px]"></TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {fields.map((field, index) => (
              <TableRow key={field.id}>
                <TableCell>
                  <input
                    type="hidden"
                    {...register(`productionList.${index}.supplyType`)}
                    defaultValue={field.supplyType ?? ''}
                  />
                  {field.supplyType}
                </TableCell>
                <TableCell>
                  <input
                    type="hidden"
                    {...register(`productionList.${index}.quantity`)}
                    defaultValue={field.quantity ?? ''}
                  />
                  <input
                    type="hidden"
                    {...register(`productionList.${index}.unit`)}
                    defaultValue={field.unit ?? ''}
                  />
                  {field.quantity} {field.unit}
                </TableCell>
                <TableCell>
                  <Button
                    variant="ghost"
                    size="icon"
                    type="button"
                    onClick={(e) => {
                      e.preventDefault();
                      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 datos de producción registrados
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}
