import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { QRCodeSVG } from 'qrcode.react';
import { apiPath } from "../../auth/utils";

import {
  Box,
  Button,
  Typography,
  TextField,
  Card,
  CardContent,
  Alert,
  CircularProgress
} from '@mui/material';

const Profile = () => {
  const [qrUrl, setQrUrl] = useState('');
  const [code, setCode] = useState('');
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState('');
  const [error, setError] = useState('');
  const [is2FAEnabled, setIs2FAEnabled] = useState(false);

  // Fetch real 2FA status from backend on mount and after actions
  const fetch2FAStatus = async () => {
    try {
      const response = await axios.get(`${apiPath}/2fa/status`, {
        headers: { Authorization: `Bearer ${localStorage.getItem('accessToken')}` }
      });
      setIs2FAEnabled(response.data.enabled);
    } catch (err) {
      console.error('Failed to fetch 2FA status', err);
      // Fallback to localStorage if API fails
      const userData = JSON.parse(localStorage.getItem('userData') || '{}');
      setIs2FAEnabled(!!userData.twoFactorEnabled);
    }
  };

  useEffect(() => {
    fetch2FAStatus();
  }, []);

  const start2FASetup = async () => {
    setLoading(true);
    setMessage('');
    setError('');
    try {
      const response = await axios.post(`${apiPath}/2fa/setup`, {}, {
        headers: { Authorization: `Bearer ${localStorage.getItem('accessToken')}` }
      });
      setQrUrl(response.data.otpauthUrl);
    } catch (err) {
      setError('Failed to generate QR code. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  const verifyCode = async () => {
    setLoading(true);
    setMessage('');
    setError('');
    try {
      await axios.post(`${apiPath}/2fa/verify-setup`, { code }, {
        headers: { Authorization: `Bearer ${localStorage.getItem('accessToken')}` }
      });
      setMessage(is2FAEnabled 
        ? '2FA re-bound successfully to your new device!' 
        : '2FA enabled successfully!'
      );
      setQrUrl('');
      setCode('');
      await fetch2FAStatus(); // Refresh status from backend
    } catch (err) {
      setError('Invalid or expired code. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  const disable2FA = async () => {
    if (!window.confirm('Are you sure you want to disable 2FA? This will reduce account security.')) {
      return;
    }

    setLoading(true);
    setMessage('');
    setError('');
    try {
      await axios.post(`${apiPath}/2fa/disable`, {}, {
        headers: { Authorization: `Bearer ${localStorage.getItem('accessToken')}` }
      });
      setMessage('2FA disabled successfully.');
      await fetch2FAStatus(); // Refresh status
    } catch (err) {
      setError('Failed to disable 2FA.');
    } finally {
      setLoading(false);
    }
  };

  const cancelSetup = () => {
    setQrUrl('');
    setCode('');
    setError('');
  };

  return (
    <Box sx={{ maxWidth: 800, mx: 'auto', mt: 4, p: 2 }}>
      <Typography variant="h4" gutterBottom>
        2FA
      </Typography>

      <Card sx={{ mt: 3 }}>
        <CardContent>
          <Typography variant="h6" gutterBottom>
            Two-Factor Authentication (2FA)
          </Typography>

          {loading && (
            <Box sx={{ textAlign: 'center', my: 3 }}>
              <CircularProgress />
            </Box>
          )}

          {!qrUrl ? (
            <>
              {is2FAEnabled ? (
                <Box>
                  <Alert severity="success" sx={{ mb: 2 }}>
                    2FA is enabled and bound to Microsoft Authenticator.
                  </Alert>
                  <Typography variant="body2" sx={{ mb: 3 }}>
                    If you have a new phone or lost access, you can re-bind or disable 2FA below.
                  </Typography>
                  <Button
                    variant="contained"
                    color="primary"
                    onClick={start2FASetup}
                    disabled={loading}
                    sx={{ mr: 2 }}
                  >
                    Re-bind 2FA (New Phone)
                  </Button>
                  <Button
                    variant="outlined"
                    color="error"
                    onClick={disable2FA}
                    disabled={loading}
                  >
                    Disable 2FA
                  </Button>
                </Box>
              ) : (
                <Box>
                  <Typography variant="body1" paragraph>
                    Add an extra layer of security with 2FA using Microsoft Authenticator.
                  </Typography>
                  <Button
                    variant="contained"
                    color="primary"
                    onClick={start2FASetup}
                    disabled={loading}
                  >
                    Enable 2FA
                  </Button>
                </Box>
              )}
            </>
          ) : (
            <Box sx={{ textAlign: 'center', my: 4 }}>
              <Typography variant="body1" gutterBottom>
                Scan this QR code with <strong>Microsoft Authenticator</strong>:
              </Typography>
              <QRCodeSVG value={qrUrl} size={220} level="M" />
              <Typography variant="caption" display="block" sx={{ mt: 2, mb: 3 }}>
                After scanning, enter the 6-digit code from the app:
              </Typography>
              <TextField
                label="Verification Code"
                value={code}
                onChange={(e) => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
                inputProps={{ maxLength: 6 }}
                sx={{ width: 200 }}
                autoFocus
              />
              <Box sx={{ mt: 3 }}>
                <Button
                  variant="contained"
                  color="primary"
                  onClick={verifyCode}
                  disabled={loading || code.length !== 6}
                >
                  {loading ? <CircularProgress size={24} /> : 'Verify'}
                </Button>
                <Button
                  variant="text"
                  onClick={cancelSetup}
                  sx={{ ml: 2 }}
                >
                  Cancel
                </Button>
              </Box>
            </Box>
          )}

          {message && (
            <Alert severity="success" sx={{ mt: 3 }}>
              {message}
            </Alert>
          )}
          {error && (
            <Alert severity="error" sx={{ mt: 3 }}>
              {error}
            </Alert>
          )}
        </CardContent>
      </Card>
    </Box>
  );
};

export default Profile;