"use client";
import React, { useState } from "react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { addLocalOffsetFromDate, cn, formatDate } from "@/lib/utils";
import moment from "moment";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Button } from "@/components/ui/button";
import { Calendar } from "@/components/ui/calendar";
import useLogPage from "../hooks/useLogPage";
import {
  EmplyPlaceHolder,
  EmptyContent,
  EmptyIcon,
  EmptyTitle,
} from "@/components/EmplyPlaceHolder";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { CalendarIcon } from "lucide-react";
import Loading from "@/components/Loading";

const LogEventsPage = () => {
  const {
    onSubmit,
    isInputChanged,
    results,
    cursor,
    isPending,
    isError,
    form,
    setPaginationParams,
  } = useLogPage();

  // Estado para la ordenación
  const [sortConfig, setSortConfig] = useState<{
    key: string;
    direction: "asc" | "desc";
  }>({ key: "id", direction: "desc" });

  // Función para manejar el clic en el encabezado
  const handleSort = (column: string) => {
    setSortConfig((prev) => {
      if (prev.key === column) {
        return {
          key: column,
          direction: prev.direction === "asc" ? "desc" : "asc",
        };
      }
      return { key: column, direction: "asc" };
    });
  };

  // Función para aplicar la ordenación
  const sortedResults = React.useMemo(() => {
    if (!results) {
      return results;
    }
    const { key, direction } = sortConfig;
    return [...results].sort((a: any, b: any) => {
      if (a[key] < b[key]) {
        return direction === "asc" ? -1 : 1;
      }
      if (a[key] > b[key]) {
        return direction === "asc" ? 1 : -1;
      }
      return 0;
    });
  }, [results, sortConfig]);

  if (isError) {
    return (
      <div className="min-h-[300px] grid place-content-center">
        <EmplyPlaceHolder>
          <EmptyIcon iconName="error"></EmptyIcon>
          <EmptyTitle className="text-base">Algo salió mal</EmptyTitle>
          <EmptyContent className="text-xs">
            Por favor, revisa tu conexión a internet o intenta más tarde.
          </EmptyContent>
        </EmplyPlaceHolder>
      </div>
    );
  }
  
  if(isPending){
    return(
      <div className="grid place-content-center min-h-[60vh]">
        <Loading/>
      </div>
    )
  }

  return (
    <section className="md:ml-4 pl-4 pb-5">
      <div className="mt-5 ">
        <div className="mb-5">
          <Form {...form}>
            <form
              onSubmit={form.handleSubmit(onSubmit)}
              className="mt-10 flex gap-3 items-end mb-4"
            >
              <div className=" flex flex-wrap gap-2">
                <div className="w-fit">
                  <FormField
                    control={form.control}
                    name="startDate"
                    render={({ field }) => (
                      <FormItem className="flex flex-col ">
                        <FormLabel>Fecha de inicio</FormLabel>
                        <Popover>
                          <PopoverTrigger asChild>
                            <FormControl>
                              <Button
                                variant={"outline"}
                                className={cn(
                                  "w-[240px] pl-3 text-left font-normal",
                                  !field.value && "text-muted-foreground"
                                )}
                              >
                                {field.value ? (
                                  formatDate(field.value)
                                ) : (
                                  <span>Pick a date</span>
                                )}
                                <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
                              </Button>
                            </FormControl>
                          </PopoverTrigger>
                          <PopoverContent className="w-auto p-0" align="start">
                            <Calendar
                              mode="single"
                              selected={field.value}
                              onSelect={field.onChange}
                              initialFocus
                            />
                          </PopoverContent>
                        </Popover>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>

                <div
                  className="
        "
                >
                  <FormField
                    control={form.control}
                    name="endDate"
                    render={({ field }) => (
                      <FormItem className="flex flex-col ">
                        <FormLabel>Fecha final</FormLabel>
                        <Popover>
                          <PopoverTrigger asChild>
                            <FormControl>
                              <Button
                                variant={"outline"}
                                className={cn(
                                  "w-[240px] pl-3 text-left font-normal",
                                  !field.value && "text-muted-foreground"
                                )}
                              >
                                {field.value ? (
                                  formatDate(field.value)
                                ) : (
                                  <span>Pick a date</span>
                                )}
                                <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
                              </Button>
                            </FormControl>
                          </PopoverTrigger>
                          <PopoverContent className="w-auto p-0" align="start">
                            <Calendar
                              mode="single"
                              selected={field.value}
                              onSelect={field.onChange}
                              initialFocus
                            />
                          </PopoverContent>
                        </Popover>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              </div>
              <div className="flex-1 space-x-2 ">
                <Button disabled={!isInputChanged} type="submit">
                  Filtrar
                </Button>
                <Button
                  className="m-auto mt-5 bg-yellow-500 hover:bg-yellow-300"
                  disabled={!cursor || isPending}
                  onClick={() => {
                    setPaginationParams((prev: any) => ({
                      ...prev,
                      cursor: cursor,
                    }));
                  }}
                >
                  {isPending ? "Cargando..." : "Ver más"}
                </Button>
              </div>
            </form>
          </Form>
        </div>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead onClick={() => handleSort("id")}>
                <div className="flex gap-1">
                  <span>Id</span>{" "}
                  <span className=" inline-block">
                    {sortConfig.key === "id" &&
                      (sortConfig.direction === "asc" ? "↑" : "↓")}
                  </span>
                </div>
              </TableHead>
              <TableHead onClick={() => handleSort("eventType")}>
                <div className="flex gap-1">
                  <span>Tipo</span>{" "}
                  {sortConfig.key === "eventType" &&
                    (sortConfig.direction === "asc" ? "↑" : "↓")}
                </div>
              </TableHead>
              <TableHead
                onClick={() => handleSort("modifiedItem")}
                className="min-w-[150px]"
              >
                <div className="flex gap-1 items-center">
                  <span>Elemento modificado </span>
                  {sortConfig.key === "modifiedItem" &&
                    (sortConfig.direction === "asc" ? "↑" : "↓")}
                </div>
              </TableHead>
              <TableHead onClick={() => handleSort("user")}>
                <div className="flex gap-1">
                  <span>Usuario</span>{" "}
                  {sortConfig.key === "user" &&
                    (sortConfig.direction === "asc" ? "↑" : "↓")}
                </div>
              </TableHead>
              <TableHead
                onClick={() => handleSort("createdAt")}
                className="min-w-[150px]"
              >
                <div className="flex gap-1">
                  <span>Fecha</span>{" "}
                  {sortConfig.key === "createdAt" &&
                    (sortConfig.direction === "asc" ? "↑" : "↓")}
                </div>
              </TableHead>
              <TableHead className="min-w-[150px]">Valores antiguos</TableHead>
              <TableHead className="min-w-[150px]">Valores nuevos</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody className="min-h-[400px]">
            {sortedResults?.map((logItem: any) => (
              <TableRow key={logItem?.id}>
                <TableCell className="font-medium">{logItem?.id}</TableCell>
                <TableCell>{logItem?.eventType}</TableCell>
                <TableCell>{logItem?.modifiedItem}</TableCell>
                <TableCell>{logItem?.user?.firstName}</TableCell>
                <TableCell>
                  {logItem?.createdAt
                    ? moment(addLocalOffsetFromDate(logItem?.createdAt)).format(
                        "dddd, D [de] MMMM YYYY, h:mm A"
                      )
                    : "-"}
                </TableCell>
                {/* Celdas omitidas por brevedad */}
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
    </section>
  );
};

export default LogEventsPage;
