import { AppContext } from "@/src/pages/_app";
import fetchApi from "@/twui/components/utils/fetch/fetchApi";
import ImageUpload from "@/twui/components/form/ImageUpload";
import Input from "@/twui/components/form/Input";
import Button from "@/twui/components/layout/Button";
import Divider from "@/twui/components/layout/Divider";
import Row from "@/twui/components/layout/Row";
import Span from "@/twui/components/layout/Span";
import Stack from "@/twui/components/layout/Stack";
import { APIResponseObject } from "@moduletrace/datasquirel/dist/package-shared/types";
import { useContext } from "react";
import useSettingsForm from "../(hooks)/use-settings-form";
import { APIReqObject } from "@/src/types";

export default function SettingsForm() {
    const { setToast, pageProps } = useContext(AppContext);
    const { formData, setFormData, loading, setLoading, user } =
        useSettingsForm();

    const deployment_user = pageProps.deployment_user;

    async function handleSubmit() {
        if (!formData.first_name?.match(/./)) return;

        setLoading(true);

        try {
            const res = await fetchApi<APIReqObject, APIResponseObject>(
                `/api/admin/settings`,
                {
                    method: "POST",
                    body: {
                        new_user: formData,
                    },
                },
            );

            if (res.success) {
                setToast({
                    toastOpen: true,
                    toastMessage: "Settings saved",
                    toastStyle: "success",
                    closeDelay: 3000,
                });
                window.location.reload();
            } else {
                setToast({
                    toastOpen: true,
                    toastMessage: res.msg || "Failed to save settings",
                    toastStyle: "error",
                    closeDelay: 4000,
                });
            }
        } finally {
            setLoading(false);
        }
    }

    if (!deployment_user?.id) {
        return null;
    }

    return (
        <Stack className="w-full max-w-[600px] items-stretch gap-6">
            <Stack className="gap-1">
                <Span size="small" variant="faded">
                    Username
                </Span>
                <Span>
                    <strong>
                        {user.super_admin
                            ? "root"
                            : deployment_user?.username || "—"}
                    </strong>
                </Span>
            </Stack>

            <Divider />

            <Row className="gap-4 items-stretch">
                <Input
                    title="First Name"
                    placeholder="Eg. John"
                    value={formData.first_name}
                    changeHandler={(v) =>
                        setFormData((prev) => ({ ...prev, first_name: v }))
                    }
                    required
                    showLabel
                />
                <Input
                    title="Last Name"
                    placeholder="Eg. Doe"
                    value={formData.last_name}
                    changeHandler={(v) =>
                        setFormData((prev) => ({ ...prev, last_name: v }))
                    }
                    showLabel
                />
            </Row>

            <Input
                title="Email"
                placeholder="Eg. john@example.com"
                type="email"
                value={formData.email}
                changeHandler={(v) =>
                    setFormData((prev) => ({ ...prev, email: v }))
                }
                required
                showLabel
            />

            <ImageUpload
                label="Profile Image"
                existingImageUrl={formData.image || undefined}
                onChangeHandler={(imgData) => {
                    setFormData((prev) => ({
                        ...prev,
                        image: imgData?.imageBase64Full || prev.image,
                    }));
                }}
                className="h-[200px]"
            />

            <Button
                title="Save Settings"
                loading={loading}
                onClick={handleSubmit}
            >
                Save Settings
            </Button>
        </Stack>
    );
}
