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';
import { TrainingSchema } from '../schemas/training';

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

// 1. Definimos la estructura de los datos para que TypeScript no se queje
// ProductItem y ProductFormValues locales eliminados en favor de TrainingSchema

export function ProductActivityList() {
  const { control, register } = useFormContext<TrainingSchema>();

  const { fields, append, remove } = useFieldArray({
    control,
    name: 'productList',
  });

  const [isOpen, setIsOpen] = useState(false);

  // Modal Form State
  const [newItem, setNewItem] = useState<any>({
    description: '',
    dailyCount: '',
    weeklyCount: '',
    monthlyCount: '',
  });

  const handleAdd = () => {
    if (newItem.description) {
      append(newItem);
      setNewItem({
        description: '',
        dailyCount: '',
        weeklyCount: '',
        monthlyCount: '',
      });
      setIsOpen(false);
    }
  };

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <h3 className="text-lg font-medium">Datos de Actividad Productiva</h3>
        <Dialog open={isOpen} onOpenChange={setIsOpen}>
          <DialogTrigger asChild>
            <Button variant="outline">Agregar Producto/Actividad</Button>
          </DialogTrigger>
          <DialogContent className="sm:max-w-[800px] max-h-[80vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>Producto Terminado</DialogTitle>
            </DialogHeader>
            <DialogDescription className="sr-only">
              Datos de actividad productiva
            </DialogDescription>
            <div className="space-y-6 py-4">
              {/* Basic Info */}
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>Descripción</Label>
                  <Input
                    value={newItem.description}
                    onChange={(e) =>
                      setNewItem({ ...newItem, description: e.target.value })
                    }
                  />
                </div>
              </div>

              <div className="grid grid-cols-3 gap-4">
                <div className="space-y-2">
                  <Label>Cant. Diario</Label>
                  <Input
                    type="number"
                    value={newItem.dailyCount}
                    onChange={(e) =>
                      setNewItem({ ...newItem, dailyCount: e.target.value })
                    }
                  />
                </div>
                <div className="space-y-2">
                  <Label>Cant. Semanal</Label>
                  <Input
                    type="number"
                    value={newItem.weeklyCount}
                    onChange={(e) =>
                      setNewItem({ ...newItem, weeklyCount: e.target.value })
                    }
                  />
                </div>
                <div className="space-y-2">
                  <Label>Cant. Mensual</Label>
                  <Input
                    type="number"
                    value={newItem.monthlyCount}
                    onChange={(e) =>
                      setNewItem({ ...newItem, monthlyCount: e.target.value })
                    }
                  />
                </div>
              </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>Producto/Descripción</TableHead>
              <TableHead>Producción Diario</TableHead>
              <TableHead>Producción Semanal</TableHead>
              <TableHead>Producción Mensual</TableHead>
              <TableHead className="w-[50px]"></TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {fields.map((field, index) => (
              <TableRow key={field.id}>
                <TableCell>
                  <input
                    type="hidden"
                    {...register(`productList.${index}.description`)}
                    defaultValue={field.description ?? ''}
                  />
                  <input
                    type="hidden"
                    {...register(`productList.${index}.dailyCount`)}
                    defaultValue={field.dailyCount ?? ''}
                  />
                  <input
                    type="hidden"
                    {...register(`productList.${index}.weeklyCount`)}
                    defaultValue={field.weeklyCount ?? ''}
                  />
                  <input
                    type="hidden"
                    {...register(`productList.${index}.monthlyCount`)}
                    defaultValue={field.monthlyCount ?? ''}
                  />
                  {field.description}
                </TableCell>
                <TableCell>{field.dailyCount}</TableCell>
                <TableCell>{field.weeklyCount}</TableCell>
                <TableCell>{field.monthlyCount}</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 productos registrados
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}
