import React, { useState } from 'react';
import { TextInput, Button, Title, Stack, Radio, Group, Text, Divider, LoadingOverlay, Box, Modal, Card, Checkbox } from '@mantine/core';
import { notifications } from '@mantine/notifications';

export default function UserConfiguration() {
  const [CIF, setCIF] = useState('');
  const [userDetails, setUserDetails] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [savingsAccount, setSavingsAccount] = useState<string | null>(null);
  const [accountError, setAccountError] = useState<string>('');
  const [detailsExpanded, setDetailsExpanded] = useState(true);
  const [showPreviewModal, setShowPreviewModal] = useState(false);
  const [confirmedPreview, setConfirmedPreview] = useState(false);
  const [ibEnabled, setIbEnabled] = useState(false);
  const [ibAccess,setIbAccess] =useState<"read"|"transaction"|"">("");
  const [mbEnabled, setMbEnabled] = useState(false);
  const [mbAccess,setMbAccess] =useState<"read"|"transaction"|"">("");
  const isValidated = !!userDetails;
  const canSubmit = isValidated && !!savingsAccount && confirmedPreview;

  const handleValidate = async () => {
    if (!CIF) {
      notifications.show({
        color: 'red',
        title: 'CIF Missing',
        message: 'Please enter a CIF number to proceed.'
      });
      return;
    }
    setLoading(true);
    setAccountError('');
    setSavingsAccount(null);
    setUserDetails(null);

    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',
          'Authorization': `Bearer ${token}`
        },
      });

      const data = await response.json();
      if (response.ok && Array.isArray(data) && data.length > 0) {
        const saAccount = data.find(acc => acc.stAccountType === 'SA');
        console.log(saAccount);
        if (saAccount) {
          setSavingsAccount(saAccount.stAccountNo);
        } else {
          setAccountError('At least one savings account is required for requesting.');
        }

        const user = data[0];
        setUserDetails({
          name: user.custname,
          userId: user.id,
          mobile: user.mobileno,
          address: user.custaddress,
          activeAccount: user.activeAccounts,
        });
      } else {
        throw new Error('User not found or data format incorrect');
      }
    } catch (err: any) {
      notifications.show({
        color: 'red',
        title: 'Validation Failed',
        message: 'User not found',
      });
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = () => {
    if (!canSubmit) {
      notifications.show({
        color: 'red',
        title: 'Required',
        message: 'One savings account is required for enable rights',
      });
      return;
    }
    else {
      const rightsData = {
        CIF,
        // internetBanking,
        // mobileBanking,
      };
      console.log('Submitting rights:', rightsData);
      notifications.show({
        color: 'blue',
        title: 'Submitted',
        message: `User -${CIF} rights submitted successfully.`,
      });
    }
    setSavingsAccount(null);
    setUserDetails(null);
    setCIF('');
  };

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

  return (
    <Box>
      <LoadingOverlay visible={loading} zIndex={1000} />
      <Title order={4}>User Configuration</Title>
      <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);
        }}
        disabled={isValidated}
        withAsterisk />

      {isValidated && (
        <>
          <Divider size="xs" label="User Info" />
          <Box style={{ overflowX: 'auto', border: '1px solid #eee', borderRadius: 8, padding: 12 }}>
            <Group p="apart">
              <Text fw={500}>Preview User Details</Text>
              <Button variant="subtle" size="xs" onClick={() => setDetailsExpanded((v) => !v)}>
                {detailsExpanded ? '▲' : '▼'}
              </Button>
            </Group>

            {detailsExpanded && (
              <>
                <Group grow>
                  <TextInput label="User ID" value={userDetails.userId} readOnly disabled />
                  <TextInput label="Name" value={userDetails.name} readOnly disabled />
                  <TextInput label="Mobile" value={userDetails.mobile} readOnly disabled />
                </Group>
                <Group grow>
                  <TextInput label="Address" value={userDetails.address} readOnly disabled />
                  <TextInput label="Savings Account" value={savingsAccount || ''} readOnly disabled />
                  <TextInput label="Active Accounts" value={userDetails.activeAccount} readOnly disabled />
                </Group>
              </>
            )}
          </Box>

          <Divider label='Rights' size="xs" />
          <Stack>
            <Group grow>
              <Box>
                <Text fw={500}>Internet Banking</Text>
                <Group mt="xs">
                  <Checkbox
                    label="Enabled"
                    checked={ibEnabled}
                    onChange={(e) => {
                      setIbEnabled(e.currentTarget.checked);
                      if (!e.currentTarget.checked) setIbAccess(""); // reset if disabled
                    }}
                  />
                  <Checkbox
                    label="Read"
                    disabled={!ibEnabled}
                    checked={ibAccess === "read"}
                    onChange={() => setIbAccess("read")}
                  />
                  <Checkbox
                    label="Transaction"
                    disabled={!ibEnabled}
                    checked={ibAccess === "transaction"}
                    onChange={() => setIbAccess("transaction")}
                  />
                </Group>
              </Box>

              {/* Mobile Banking */}
              <Box>
                <Text fw={500}>Mobile Banking</Text>
                <Group mt="xs">
                  <Checkbox
                    label="Enabled"
                    checked={mbEnabled}
                    onChange={(e) => {
                      setMbEnabled(e.currentTarget.checked);
                      if (!e.currentTarget.checked) setMbAccess(""); // reset if disabled
                    }}
                  />
                  <Checkbox
                    label="Read"
                    disabled={!mbEnabled}
                    checked={mbAccess === "read"}
                    onChange={() => setMbAccess("read")}
                  />
                  <Checkbox
                    label="Transaction"
                    disabled={!mbEnabled}
                    checked={mbAccess === "transaction"}
                    onChange={() => setMbAccess("transaction")}
                  />
                </Group>
              </Box>
            </Group>
          </Stack>
          {accountError && (
            <Text color="red" size="sm" mt="xs">{accountError}</Text>
          )}

        </>
      )}

      <Button mt="lg" onClick={handleMainAction} disabled={loading}>
        {!isValidated ? 'Validate' : !confirmedPreview ? 'Preview' : 'Submit'}
      </Button>

      <Modal
        opened={showPreviewModal}
        onClose={() => setShowPreviewModal(false)}
        title="Confirm User Rights"
        centered
      >
        <Stack>
          <TextInput label="CIF" value={CIF} readOnly disabled />
          {/* <TextInput label="Internet Banking" value={internetBanking} readOnly disabled />
          <TextInput label="Mobile Banking" value={mobileBanking} readOnly disabled /> */}
        </Stack>
        <Group p="right" mt="md">
          <Button variant="default" onClick={() => setShowPreviewModal(false)}>Cancel</Button>
          <Button onClick={() => { setConfirmedPreview(true); setShowPreviewModal(false); }}>OK</Button>
        </Group>
      </Modal>
    </Box>

  );
}