'use client';
import { useState, useEffect } from "react";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { FormValues, createForm } from "./schema";
import { FormUpdateNewLivingSpace } from "./form";
import { useUpdateLivingSpaceMutation } from "./queries";
import { Button } from "@/components/ui/button";
import { IconArrowLeftToArc } from "@tabler/icons-react";
import { useRouter } from "next/navigation";
import { useGraphQlLivingSpaceList } from "../list/queries";
import { useSearchParams } from "next/navigation";

import PageLivingSpaceBuildsTableSection from "../tables/builds/page";
import PageLivingSpaceUserTypesTableSection from "../tables/userType/page";
import PageLivingSpacePartsTableSection from "../tables/part/page";
import PageLivingSpacePersonTableSection from "../tables/person/page";
import PageLivingSpaceCompanyTableSection from "../tables/company/page";

const PageLivingSpaceUpdate = () => {

    const router = useRouter();
    const searchParams = useSearchParams()
    const uuid = searchParams?.get('uuid') || null
    const buildIDFromUrl = searchParams?.get('buildID') || null
    const [page, setPage] = useState(1);
    const [limit, setLimit] = useState(10);
    const [sort, setSort] = useState({ createdAt: 'desc' });
    const [filters, setFilters] = useState({});

    const backToBuildAddress = <><div>UUID not found in search params</div><Button onClick={() => router.push('/living-spaces')}>Back to Living Space List</Button></>
    const { data, isLoading, refetch } = useGraphQlLivingSpaceList(buildIDFromUrl || '', { limit, skip: (page - 1) * limit, sort, filters: { ...filters, uuid } });
    const initData = data?.data?.[0] || null;
    const [userTypeID, setUserTypeID] = useState<string | null>(null);
    const isPartInit = initData?.part !== null ? true : false;
    const [isProperty, setIsProperty] = useState<boolean | null>(isPartInit);
    const [partID, setPartID] = useState<string | null>(null);
    const [companyID, setCompanyID] = useState<string | null>(null);
    const [personID, setPersonID] = useState<string | null>(null);
    const form = createForm({ userTypeID: initData?.userType || "", partID: initData?.part || "", companyID: initData?.company || "", personID: initData?.person || "" });

    useEffect(() => {
        if (initData) {
            form.setValue("userTypeID", initData?.userType || ""); form.setValue("partID", initData?.part || ""); form.setValue("companyID", initData?.company || "");
            form.setValue("personID", initData?.person || ""); form.setValue("expiryStarts", initData?.expiryStarts || ""); form.setValue("expiryEnds", initData?.expiryEnds || "");
            setUserTypeID(initData?.userType || ""); setPartID(initData?.part || ""); setCompanyID(initData?.company || ""); setPersonID(initData?.person || "");
        }
    }, [initData])
    useEffect(() => {
        form.setValue("userTypeID", userTypeID || ""); form.setValue("partID", partID || ""); form.setValue("companyID", companyID || ""); form.setValue("personID", personID || "");
    }, [userTypeID, partID, companyID, personID, form]);

    const mutation = useUpdateLivingSpaceMutation();
    function onSubmit(values: FormValues) { mutation.mutate({ data: values, uuid: uuid || "", buildID: buildIDFromUrl || "" }) }
    const [isUserTypeEnabled, setIsUserTypeEnabled] = useState(true);
    const [isPartsEnabled, setIsPartsEnabled] = useState(false);
    const [isHandleCompanyAndPersonEnable, setIsHandleCompanyAndPersonEnable] = useState(true);

    useEffect(() => { if (!!isProperty) { setIsPartsEnabled(true) } else { setPartID(null); setIsPartsEnabled(false) } }, [isProperty])
    useEffect(() => { if (isPartInit) { setIsPartsEnabled(true) } else { setIsPartsEnabled(false) } }, [isPartInit])

    if (!uuid) { return backToBuildAddress }; if (!initData) { return backToBuildAddress }
    const tabsClassName = "border border-gray-300 rounded-sm h-10"

    return <>
        <div className="flex flex-col m-7">
            <Tabs defaultValue="usertype" className="w-full">
                <Button className="my-3 h-10" variant="outline" size="sm" onClick={() => { router.push("/living-spaces") }}>
                    <IconArrowLeftToArc /><span className="hidden lg:inline">Back to Living Space List</span>
                </Button>
                <TabsList className="grid w-full grid-flow-col auto-cols-fr gap-1.5">
                    {isUserTypeEnabled && <TabsTrigger className={tabsClassName} value="usertype">User Type</TabsTrigger>}
                    {isPartsEnabled && <TabsTrigger className={tabsClassName} value="parts">Parts</TabsTrigger>}
                    {isHandleCompanyAndPersonEnable && <TabsTrigger className={tabsClassName} value="company">Company</TabsTrigger>}
                    {isHandleCompanyAndPersonEnable && <TabsTrigger className={tabsClassName} value="person">Person</TabsTrigger>}
                </TabsList>
                <div className="mt-6">
                    {isUserTypeEnabled && <TabsContent value="usertype">
                        <PageLivingSpaceUserTypesTableSection userTypeID={userTypeID} setUserTypeID={setUserTypeID} setIsProperty={setIsProperty} setIsPartsEnabled={setIsPartsEnabled} setIsHandleCompanyAndPersonEnable={setIsHandleCompanyAndPersonEnable} />
                    </TabsContent>}
                    {isPartsEnabled && buildIDFromUrl && <TabsContent value="parts">
                        <PageLivingSpacePartsTableSection buildId={buildIDFromUrl} partID={partID} setPartID={setPartID} setIsPartsEnabled={setIsPartsEnabled} />
                    </TabsContent>}
                    {isHandleCompanyAndPersonEnable && <TabsContent value="company"><PageLivingSpaceCompanyTableSection companyID={companyID} setCompanyID={setCompanyID} /></TabsContent>}
                    {isHandleCompanyAndPersonEnable && <TabsContent value="person"><PageLivingSpacePersonTableSection personID={personID} setPersonID={setPersonID} /></TabsContent>}
                </div>
            </Tabs>
        </div>
        <div><FormUpdateNewLivingSpace form={form} onSubmit={onSubmit} /></div>
    </>
}

export { PageLivingSpaceUpdate };