"use client";
import React, { useState } from "react";
import {
  TextInput,
  Button,
  Title,
  Stack,
  Group,
  Text,
  Divider,
  LoadingOverlay,
  Box,
  Modal,
  Checkbox,
  Paper,
  Tabs,
  ScrollArea,
  Center,
} from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { useRouter } from "next/navigation";
import { IconGavel, IconHome, IconUser } from "@tabler/icons-react";

export default function UserConfiguration() {
  const router = useRouter();
  const [CIF, setCIF] = useState("");
  const [userDetails, setUserDetails] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [savingsAccount, setSavingsAccount] = useState<string | null>(null);
  const [showPreviewModal, setShowPreviewModal] = useState(false);
  const [confirmedPreview, setConfirmedPreview] = useState(false);
  const [ibEnabled, setIbEnabled] = useState(false);
  const [ibAccess, setIbAccess] = useState<"2" | "1" | null>(null);
  const [mbEnabled, setMbEnabled] = useState(false);
  const [mbAccess, setMbAccess] = useState<"2" | "1" | null>(null);
  const [ibLimit, setIbLimit] = useState("");
  const [mbLimit, setMbLimit] = useState("");
  const [error, setError] = useState<string | null>(null);

  const isValidated = !!userDetails;
  const canSubmit =
    isValidated && savingsAccount && userDetails?.mobile && confirmedPreview;

  // 🔹 Fetch both user details and rights
  const handleValidate = async () => {
    if (!CIF) {
      notifications.show({
        color: "red",
        title: "CIF Missing",
        message: "Please enter a CIF number to proceed.",
      });
      return;
    }
    setLoading(true);
    try {
      const token = localStorage.getItem("admin_access_token");
      const response = await fetch(
        `/api/auth/admin/fetch/customer_details?CIF=${CIF}`,
        {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
            "X-Login-Type": "Admin",
            Authorization: `Bearer ${token}`,
          },
        }
      );
      const data = await response.json();
      if (!response.ok || !Array.isArray(data) || data.length === 0) {
        
        setError("User not present or invalid CIF number.");
      }
      const saAccount = data.find(
        (acc: { stAccountType: string; }) => acc.stAccountType === "SA" || acc.stAccountType === "SB"
      );
      setSavingsAccount(saAccount?.stAccountNo ?? null);

      const user = data[0];
      setUserDetails({
        name: user.custname,
        userId: user.id,
        mobile: user.mobileno ?? null,
        address: user.custaddress,
        activeAccount: user.activeAccounts,
        branchNo: user.stBranchNo,
        dateOfBirth: user.custdob,
        pinCode: user.pincode,
      });
      // Fetch existing rights if any
      const rightsRes = await fetch(
        `/api/auth/admin/user/rights?CIF=${CIF}`,
        {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
            "X-Login-Type": "Admin",
            Authorization: `Bearer ${token}`,
          },
        }
      );

      if (rightsRes.ok) {
        const rights = await rightsRes.json();
        if (rights?.ib_access_level || rights?.mb_access_level) {
          // populate existing rights
          if (rights.ib_access_level) {
            setIbEnabled(true);
            setIbAccess(rights.ib_access_level as "1" | "2");
            setIbLimit(rights.inb_limit_amount?.toString() || "");
          }
          if (rights.mb_access_level) {
            setMbEnabled(true);
            setMbAccess(rights.mb_access_level as "1" | "2");
            setMbLimit(rights.mobile_limit_amount?.toString() || "");
          }
        }
      }

    } 
    catch (err) {
      console.error(err);
      setError("User not present or invalid CIF number.");
    } finally {
      setLoading(false);
    }
  };

  // Preview before submit
  const handlePreview = () => {
    if (!savingsAccount || !userDetails?.mobile) return;
    if (!ibAccess && !mbAccess) {
      notifications.show({
        title: "Rights Required",
        message:
          "Please select at least one right (Internet Banking or Mobile Banking).",
        color: "red",
      });
      return;
    }
    if ((ibEnabled && !ibLimit) || (mbEnabled && !mbLimit)) {
      notifications.show({
        title: "Limit Required",
        message: "Please enter fund transfer limits for enabled services.",
        color: "red",
      });
      return;
    }
    setShowPreviewModal(true);
  };

  // Submit or update rights
  const handleSubmit = async () => {
    if (!canSubmit) return;
    try {
      const token = localStorage.getItem("admin_access_token");
      const response = await fetch("/api/auth/admin/user/rights", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-Login-Type": "Admin",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({
          CIF,
          ib_access_level: ibAccess,
          mb_access_level: mbAccess,
          ib_limit: ibLimit ? parseInt(ibLimit) : 0,
          mb_limit: mbLimit ? parseInt(mbLimit) : 0,
        }),
      });

      const data = await response.json();
      if (response.ok) {
        if (data?.otp) {
          await fetch("/api/otp/send", {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
              "X-Login-Type": "Admin",
            },
            body: JSON.stringify({
              mobileNumber: userDetails.mobile,
              type: "REGISTRATION",
              userOtp: data.otp,
            }),
          });
          notifications.show({
            color: "blue",
            title: "Submitted",
            message: `User ${CIF} rights submitted successfully. OTP sent to the user.`,
          });
        } else if (data?.message) {
          await fetch("/api/otp/send", {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
              "X-Login-Type": "Admin",
            },
            body: JSON.stringify({
              mobileNumber: userDetails.mobile,
              type: "RIGHT_UPDATE",
            }),
          });
          notifications.show({
            color: "blue",
            title: "Updated",
            message: `User ${CIF} rights updated successfully. Confirmation sent to the user.`,
          });
        }
      } else if (
        response.status === 401 ||
        data.message === "invalid or expired token"
      ) {
        localStorage.clear();
        sessionStorage.clear();
        router.push("/administrator/login");
      }
    } catch (err) {
      console.error(err);
      notifications.show({
        color: "red",
        title: "Failed - Right",
        message: `Cannot process user ${CIF} rights.`,
        autoClose: false,
      });
    } finally {
      handleReset();
    }
  };

  const handleReset = () => {
    setSavingsAccount(null);
    setUserDetails(null);
    setCIF("");
    setConfirmedPreview(false);
    setIbEnabled(false);
    setIbAccess(null);
    setIbLimit("");
    setMbEnabled(false);
    setMbAccess(null);
    setMbLimit("");
  };

  const handleMainAction = () => {
    if (!isValidated) handleValidate();
    else if (!confirmedPreview) handlePreview();
    else handleSubmit();
  };


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

      <Box
        style={{
          height: "65vh",
          maxHeight: "65vh",
          // overflowY: "auto",
        }}
      >
        <LoadingOverlay visible={loading} zIndex={1000} />

        <TextInput
          label="Enter CIF No"
          placeholder="Enter your CIF No"
          value={CIF}
          onChange={(e) => {
            const input = e.currentTarget.value.replace(/\D/g, "");
            if (input.length <= 11)
              setCIF(input);
            setError(null);
          }}
          disabled={isValidated}
          withAsterisk
        />
        {error && (
          <Center mt="xl">
            <Text c="red" fw={500} size="md">
              {error}
            </Text>
          </Center>
        )}

        {isValidated && (
          <Tabs defaultValue="details" mt="md" variant="outline">
            <Tabs.List>
              <Tabs.Tab value="details" leftSection={<IconUser size={12} />}>User Details</Tabs.Tab>
              <Tabs.Tab value="address" leftSection={<IconHome size={12} />}>Address</Tabs.Tab>
              <Tabs.Tab value="rights" leftSection={<IconGavel size={12} />}>Rights</Tabs.Tab>
            </Tabs.List>

            <Tabs.Panel value="details" pt="xs">
              <ScrollArea h={250} type="auto" offsetScrollbars>
                <Paper withBorder p="md" radius="md">
                  <Stack>
                    <Group grow>
                      <Text fw={700} >ID:</Text>
                      <Text>{userDetails?.userId ?? "N/A"}</Text>
                    </Group>
                    <Group grow>
                      <Text fw={700} >Branch:</Text>
                      <Text>{userDetails?.branchNo ?? "N/A"}</Text>
                    </Group>
                    <Group grow>
                      <Text fw={700} >Name:</Text>
                      <Text>{userDetails?.name ?? "N/A"}</Text>
                    </Group>
                    <Group grow>
                      <Text fw={700} >Date of Birth:</Text>
                      <Text>
                        {userDetails?.dateOfBirth
                          ? `${userDetails.dateOfBirth.slice(0, 2)}/${userDetails.dateOfBirth.slice(2, 4)}/${userDetails.dateOfBirth.slice(4)}`
                          : "N/A"}
                      </Text>
                    </Group>
                    <Group grow>
                      <Text fw={700} >Savings Account:</Text>
                      <Text c="blue">
                        {Array.isArray(savingsAccount)
                          ? savingsAccount.join(", ")
                          : savingsAccount ?? "N/A"}
                      </Text>
                    </Group>
                    <Group grow>
                      <Text fw={700}>Active Accounts:</Text>
                      <Text c="Green">{userDetails?.activeAccount ?? "N/A"}</Text>
                    </Group>
                  </Stack>
                </Paper>
              </ScrollArea>
            </Tabs.Panel>

            <Tabs.Panel value="address" pt="xs">
              <ScrollArea h={250} type="auto" offsetScrollbars>
                <Paper withBorder p="md" radius="md">
                  <Stack>
                    <Group grow>
                      <Text fw={700} >Address:</Text>
                      <Text>{userDetails?.address ?? "N/A"}</Text>
                    </Group>
                    <Group grow>
                      <Text fw={700} >Pincode:</Text>
                      <Text>{userDetails?.pinCode ?? "N/A"}</Text>
                    </Group>
                    <Group grow>
                      <Text fw={700} >Mobile Number:</Text>
                      <Text>{userDetails?.mobile ?? "N/A"}</Text>
                    </Group>
                  </Stack>
                </Paper>
              </ScrollArea>
            </Tabs.Panel>

            <Tabs.Panel value="rights" pt="xs">
              <Stack gap="md">
                {/* Internet Banking Section */}
                <Group>
                  <Box w={150}>
                    <Text fw={700}>Internet Banking</Text>
                  </Box>
                  <Box w={100}>
                    <Checkbox
                      disabled={confirmedPreview}
                      checked={ibEnabled}
                      onChange={(e) => {
                        setIbEnabled(e.currentTarget.checked);
                        if (!e.currentTarget.checked) {
                          setIbAccess(null);
                          setIbLimit("");
                        }
                      }}
                    />
                  </Box>
                  <Box w={120}>
                    <Checkbox
                      disabled={!ibEnabled || confirmedPreview}
                      checked={ibAccess === "1"}
                      onChange={() => setIbAccess("1")}
                      label="Transaction"
                    />
                  </Box>
                  <Box w={100}>
                    <Checkbox
                      disabled={!ibEnabled || confirmedPreview}
                      checked={ibAccess === "2"}
                      onChange={() => setIbAccess("2")}
                      label="Read"
                    />
                  </Box>
                </Group>
                <Group align="center" gap="sm">
                  <Text fw={700}>
                    Fund Transfer Limit for Internet Banking
                  </Text>
                  <TextInput
                    placeholder="Enter Amount"
                    value={ibLimit}
                    onChange={(e) => {
                      const val = e.currentTarget.value;
                      if (val === "" || (/^\d{0,7}$/.test(val))) {
                        setIbLimit(val);
                      }
                    }}
                  />
                </Group>

                <Divider my="sm" labelPosition="center" />

                <Group >
                  <Box w={150}>
                    <Text fw={700}>Mobile Banking</Text>
                  </Box>
                  <Box w={100}>
                    <Checkbox
                      disabled={confirmedPreview}
                      checked={mbEnabled}
                      onChange={(e) => {
                        setMbEnabled(e.currentTarget.checked);
                        if (!e.currentTarget.checked) {
                          setMbAccess(null);
                          setMbLimit("");
                        }
                      }}
                    />
                  </Box>
                  <Box w={120}>
                    <Checkbox
                      disabled={!mbEnabled || confirmedPreview}
                      checked={mbAccess === "1"}
                      onChange={() => setMbAccess("1")}
                      label="Transaction"
                    />
                  </Box>
                  <Box w={100}>
                    <Checkbox
                      disabled={!mbEnabled || confirmedPreview}
                      checked={mbAccess === "2"}
                      onChange={() => setMbAccess("2")}
                      label="Read"
                    />
                  </Box>
                </Group>
                <Group align="center" gap="sm">
                  <Text fw={700}>
                    Fund Transfer Limit for Mobile Banking
                  </Text>
                  <TextInput
                    placeholder="Enter Amount"
                    value={mbLimit}
                    onChange={(e) => {
                      const val = e.currentTarget.value;
                      if (val === "" || (/^\d{0,7}$/.test(val))) {
                        setMbLimit(val);
                      }
                    }}
                  />
                </Group>
              </Stack>
            </Tabs.Panel>
          </Tabs>
        )}

        <Modal
          opened={showPreviewModal}
          onClose={() => setShowPreviewModal(false)}
          title="Confirm User Rights"
          centered
        >
          <Stack>
            <Text>
              <strong>CIF:</strong> {CIF}
            </Text>
            <Text>
              <strong>Savings Account:</strong> {savingsAccount ?? "N/A"}
            </Text>
            <Text>
              <strong>Mobile Number:</strong> {userDetails?.mobile ?? "N/A"}
            </Text>

            <Divider label="Rights" size="xs" />

            {/* Internet Banking Section */}
            <TextInput
              label="Internet Banking Access"
              value={
                ibAccess === "1"
                  ? "Transaction"
                  : ibAccess === "2"
                    ? "Read"
                    : "No Rights"
              }
              readOnly
            />

            <TextInput
              label="Internet Banking Limit"
              value={ibLimit || "N/A"}
              readOnly
            />

            {/* Mobile Banking Section */}
            <TextInput
              label="Mobile Banking Access"
              value={
                mbAccess === "1"
                  ? "Transaction"
                  : mbAccess === "2"
                    ? "Read"
                    : "No Rights"
              }
              readOnly
            />

            <TextInput
              label="Mobile Banking Limit"
              value={mbLimit || "N/A"}
              readOnly
            />
          </Stack>

          <Group justify="right" mt="md">
            <Button variant="default" onClick={() => setShowPreviewModal(false)}>
              Cancel
            </Button>
            <Button
              onClick={() => {
                setConfirmedPreview(true);
                setShowPreviewModal(false);
              }}
              disabled={!savingsAccount || !userDetails?.mobile}
            >
              OK
            </Button>
          </Group>
        </Modal>
      </Box>

      <Group>
        <Button
          onClick={handleMainAction}
          disabled={
            loading ||
            (!isValidated && !CIF) ||
            (isValidated &&
              !confirmedPreview &&
              (!savingsAccount || !userDetails?.mobile))
          }
        >
          {!isValidated ? "Validate" : !confirmedPreview ? "Preview" : "Submit"}
        </Button>
        {isValidated && (
          <Button color="red" variant="light" onClick={handleReset}>
            Reset
          </Button>
        )}
      </Group>
    </>
  );
}
