"use client";
import { useState, useEffect } from "react";
import { useParams } from "next/navigation";
import Location from "@components/Location/Location";
import { useLocationStore } from "@store/Location.Store";
import ClientsIcon from "@mui/icons-material/AccountBoxOutlined";
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
import StorefrontOutlinedIcon from "@mui/icons-material/StorefrontOutlined";
import EmailOutlinedIcon from "@mui/icons-material/EmailOutlined";
import PhoneOutlinedIcon from "@mui/icons-material/PhoneOutlined";
import Avatar from "@components/Avatar/Avatar";
import PaginationControls from "@components/PaginationControls/PaginationControls";
import pageStyle from "./page.module.css";
import { findClientsByOrganization } from "./Clients.Service";
import {
    FindClientsParams,
    OrganizationClientsResults,
    OrganizationClientView,
    PaginateOrganizationClientsParams,
} from "@core/Models/Clients.model";
import { useNavigation } from "@hooks/goto";
import { FilterData, useFilterStore } from "@core/Store/Filter.Store";
import Filterable from "@core/app/components/Filterable/Filterable";
import Textbox from "@core/app/components/Textbox/Textbox";

type UrlData = {
    id: string;
};

type ClientParams = FilterData & FindClientsParams;

const FilterContent = () => {
    const filter = useFilterStore();
    const [filterFirstName, setFilterFirstName] = useState<string>("");
    const [filterLastName, setFilterLastName] = useState<string>("");
    const [filterEmail, setFilterEmail] = useState<string>("");

    const onChangeHandler = (field: string, value: string) => {
        const data = useFilterStore.getState().filterData as ClientParams;

        // Actualizamos el estado local según el campo modificado
        switch (field) {
            case "firstName":
                setFilterFirstName(value);
                break;
            case "lastName":
                setFilterLastName(value);
                break;
            case "email":
                setFilterEmail(value);
                break;
        }

        // Creamos el filtro actualizado
        const updatedFilter: ClientParams = {
            ...data,
            [field]: value, // Agregamos o actualizamos el campo
        };

        // Eliminamos los campos con valores vacíos
        const filteredFilter = Object.fromEntries(
            Object.entries(updatedFilter).filter(([, v]) => v && v.trim() !== "")
        );

        filter.setFilterData(filteredFilter as ClientParams);
    };

    return (
        <>
            <Textbox
                placeholder="Nombre"
                width="100%"
                value={filterFirstName}
                type="text"
                onChange={(e) => {
                    onChangeHandler("firstName", e.target.value);
                }}
            />
            <Textbox
                placeholder="Apellido"
                width="100%"
                value={filterLastName}
                type="text"
                onChange={(e) => {
                    onChangeHandler("lastName", e.target.value);
                }}
            />
            <Textbox
                placeholder="Email"
                width="100%"
                value={filterEmail}
                type="text"
                onChange={(e) => {
                    onChangeHandler("email", e.target.value);
                }}
            />
        </>
    );
};

export type ClientRow = OrganizationClientView;

export default function ClientsGrid() {
    const data = useParams<UrlData>();
    const oid = data.id;
    const location = useLocationStore();
    const eventHandler = useEventHandlerStore();
    const filter = useFilterStore();
    const { goTo } = useNavigation();

    const [pageSize] = useState<number>(
        parseInt(
            process.env.NEXT_PUBLIC_DATAGRID_PAGE_SIZE
                ? process.env.NEXT_PUBLIC_DATAGRID_PAGE_SIZE
                : "10"
        )
    );
    const [clients, setClients] = useState<OrganizationClientsResults>();

    useEffect(() => {
        eventHandler.setEventType(EVENT_TYPES.NEED_ADD);

        filter.setTitle("Filtrar Clientes");
        filter.clearFilterData();
        filter.setContent(<FilterContent />);
        filter.setOnFilter(() => {
            loadClients(1, pageSize);
        });
    }, []);

    useEffect(() => {
        location.clear();

        location.add({
            url: "/admin/org",
            title: "Mis organizaciones",
            icon: null,
        });

        location.add({
            url: "/admin/org/profile/" + oid,
            title: "Organizacion",
            icon: <StorefrontOutlinedIcon sx={{ mr: 0.5 }} fontSize="inherit" />,
        });

        location.add({
            url: "",
            title: "Clientes",
            icon: <ClientsIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });

        loadClients(1, pageSize);
    }, []);

    const loadClients = (page: number = 1, pageSize: number = 30) => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);

        const data = useFilterStore.getState().filterData;

        const filterData: PaginateOrganizationClientsParams = {
            companyId: oid,
            page: page,
            limit: pageSize,
            ...data,
        };

        findClientsByOrganization(filterData)
            .then((res) => {
                setClients(res);
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.NEED_ADD);
            });
    };

    const handleClientClick = (client: ClientRow) => {
        goTo("/admin/org/" + oid + "/client/" + client.id + "/profile");
    };

    return (
        <>
            <Filterable />
            <Location />
            <div className={pageStyle.pageContainer}>
                {clients?.data && clients.data.length > 0 ? (
                    <div className={pageStyle.clientsGrid}>
                        {clients.data.map((client) => (
                            <div
                                key={client.id}
                                className={`${pageStyle.clientCard} ${client.banned ? pageStyle.banned : ''}`}
                                onClick={() => handleClientClick(client as ClientRow)}
                            >
                                <div className={pageStyle.avatarContainer}>
                                    <Avatar
                                        src={client.avatar}
                                        alt={client.fullName}
                                        size="small"
                                        border="none"
                                    />
                                </div>
                                <div className={pageStyle.infoContainer}>
                                    <div className={pageStyle.headerRow}>
                                        <h3 className={pageStyle.clientName}>{client.fullName}</h3>
                                        {client.banned && (
                                            <span className={pageStyle.bannedBadge}>Baneado</span>
                                        )}
                                    </div>
                                    <p className={pageStyle.clientDetail}>
                                        <div className={pageStyle.iconWrapper}>
                                            <EmailOutlinedIcon sx={{ fontSize: 14 }} />
                                        </div>
                                        {client.email || "Sin email"}
                                    </p>
                                    <p className={pageStyle.clientPhone}>
                                        <div className={pageStyle.iconWrapper}>
                                            <PhoneOutlinedIcon sx={{ fontSize: 14 }} />
                                        </div>
                                        {client.phoneAreaCode && client.phoneNumber 
                                            ? `${client.phoneCountryCode || ''} ${client.phoneAreaCode} - ${client.phoneNumber}`
                                            : "Sin teléfono"
                                        }
                                    </p>
                                </div>
                            </div>
                        ))}
                    </div>
                ) : (
                    <div className={pageStyle.emptyState}>
                        No se encontraron clientes con los filtros aplicados.
                    </div>
                )}
                
                {clients && clients.pages > 1 && (
                    <div className={pageStyle.paginationWrapper}>
                        <PaginationControls
                            current={clients.page}
                            size={pageSize}
                            max={clients.pages}
                            onChange={(page, size) => loadClients(page, size)}
                        />
                    </div>
                )}
            </div>
        </>
    );
}
