"use client";

import React, { useState, useEffect } from "react";
import {
    TextInput,
    Button,
    Title,
    Stack,
    Group,
    Text,
    Paper,
    LoadingOverlay,
    Divider,
    Select,
    Center,
} from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { useRouter } from "next/navigation";

export default function UserUnlockPage() {
    const router = useRouter();
    const [CIF, setCIF] = useState("");
    const [username, setUsername] = useState("");
    const [userDetails, setUserDetails] = useState<any>(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    // Redirect if not logged in
    useEffect(() => {
        const token = localStorage.getItem("admin_access_token");
        if (!token) {
            localStorage.clear();
            sessionStorage.clear();
            router.push("/administrator/login");
        }
    }, [router]);

    const checkAuth = () => {
        const token = localStorage.getItem("admin_access_token");
        if (!token) {
            localStorage.clear();
            sessionStorage.clear();
            router.push("/administrator/login");
            return null;
        }
        return token;
    };

    // Fetch user info
    const handleSearch = async () => {
        setError(null);
        setUserDetails(null);

        if (!CIF && !username) {
            notifications.show({
                color: "red",
                title: "Missing Input",
                message: "Please enter either CIF number or username.",
            });
            return;
        }

        setLoading(true);
        const token = checkAuth();
        if (!token) return;

        try {
            const query = CIF ? CIF : username;
            const response = await fetch(`/api/auth/admin/user/rights?CIF=${query}`, {
                method: "GET",
                headers: {
                    "Content-Type": "application/json",
                    "X-Login-Type": "Admin",
                    Authorization: `Bearer ${token}`,
                },
            });

            const data = await response.json();

            if (!response.ok || !data?.customer_no) {
                setError("User not found or invalid CIF/username.");
                notifications.show({
                    color: "red",
                    title: "User Not Found",
                    message: "Invalid CIF or username.",
                });
                return;
            }

            setUserDetails(data);

            notifications.show({
                color: data.locked ? "red" : "green",
                title: "User Found",
                message: `User ${data.customer_no} is currently ${data.locked ? "Locked 🔒" : "Unlocked 🔓"
                    }`,
            });
        } catch (err) {
            console.error(err);
            notifications.show({
                color: "red",
                title: "Error",
                message: "Failed to fetch user details.",
            });
        } finally {
            setLoading(false);
        }
    };

    // 🔄 Unlock or lock user
    const handleStatusChange = async (value: string) => {
        if (!userDetails?.customer_no) return;
        const isUnlock = value === "unlocked";

        const token = checkAuth();
        if (!token) return;

        setLoading(true);
        try {
            const response = await fetch("/api/auth/admin/user/unlock", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-Login-Type": "Admin",
                    Authorization: `Bearer ${token}`,
                },
                body: JSON.stringify({
                    user: userDetails.customer_no, // can also be username if API supports
                    action: !isUnlock, // false => unlock, true => lock
                }),
            });

            const data = await response.json();

            if (response.ok) {
                setUserDetails({ ...userDetails, locked: !isUnlock });
                notifications.show({
                    color: "green",
                    title: "Success",
                    message: `User ${userDetails.customer_no} ${isUnlock ? "unlocked" : "locked"
                        } successfully.`,
                });
            } else {
                notifications.show({
                    color: "red",
                    title: "Failed",
                    message: data.message || "Unable to update lock status.",
                });
            }
        } catch (err) {
            console.error(err);
            notifications.show({
                color: "red",
                title: "Error",
                message: "Something went wrong while updating user status.",
            });
        } finally {
            setLoading(false);
        }
    };

    const handleReset = () => {
        setCIF("");
        setUsername("");
        setUserDetails(null);
        setError(null);
    };

    return (
        <>
            <Title order={4}>User Unlock Management</Title>

            <Paper p="md" mt="md" radius="md" withBorder>
                <LoadingOverlay visible={loading} zIndex={1000} />

                <Group grow>
                    <TextInput
                        label="CIF Number"
                        placeholder="Enter CIF Number"
                        value={CIF}
                        onChange={(e) => {
                            const input = e.currentTarget.value.replace(/\D/g, "");
                            if (input.length <= 11) setCIF(input);
                            setError(null);
                        }}
                        disabled={!!username}
                    />

                    <Text c="dimmed" ta="center">
                        OR
                    </Text>

                    <TextInput
                        label="Username"
                        placeholder="Enter Username"
                        value={username}
                        onChange={(e) => {
                            const sanitized = e.currentTarget.value.replace(/[^a-zA-Z0-9@_]/g, "");
                            if (sanitized.length <= 15) setUsername(sanitized);
                            setError(null);
                        }}
                        disabled={!!CIF}
                    />
                </Group>

                {error && (
                    <Center mt="xs">
                        <Text c="red" size="sm" fw={500}>
                            {error}
                        </Text>
                    </Center>
                )}

                <Group mt="md">
                    <Button onClick={handleSearch} disabled={loading}>
                        Search
                    </Button>
                    <Button variant="light" color="red" onClick={handleReset}>
                        Reset
                    </Button>
                </Group>
            </Paper>

            {userDetails && (
                <Paper withBorder p="md" mt="xl" radius="md">
                    <Stack gap="xs">
                        <Divider label="User Details" labelPosition="center" />

                        <Text>
                            <strong>Customer No:</strong> {userDetails.customer_no}
                        </Text>

                        <Text>
                            <strong>Registration Status:</strong>{" "}
                            {userDetails.last_login === null ? (
                                <Text span c="red" fw={600}>
                                    Not Registered
                                </Text>
                            ) : (
                                <Text span c="green" fw={600}>
                                    Registered
                                </Text>
                            )}
                        </Text>

                        <Select
                            label="Locked Status"
                            value={userDetails.locked ? "locked" : "unlocked"}
                            data={[
                                { value: "locked", label: "Locked 🔒" },
                                { value: "unlocked", label: "Unlocked 🔓" },
                            ]}
                            onChange={(value) => {
                                if (!value) return;
                                handleStatusChange(value);
                            }}
                            mt="md"
                            disabled={!userDetails.locked} // only allow change if locked
                        />
                    </Stack>
                </Paper>
            )}
        </>
    );
}
