import React, { useEffect, useMemo, useRef, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { Box, Card, CardContent, CardHeader, Typography, Stack, Button, Alert, CircularProgress, Snackbar } from "@mui/material";
import { useSession } from "../../context/sessioncontext";

type KycState = "Pending" | "Approved" | "Rejected" | "Cancelled" | "Unknown";

const API_BASE = (process.env as any)?.REACT_APP_API_URL_DIDIT;

const KycStatus: React.FC = () => {
  const { isLoggedIn } = useSession();
  const navigate = useNavigate();
  const location = useLocation();
  const [status, setStatus] = useState<KycState>("Pending");
  const [loading, setLoading] = useState<boolean>(true);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const [sessionId, setSessionId] = useState<string>("");
  const timer = useRef<number | null>(null);
  const [snack, setSnack] = useState<{ open: boolean; message: string; severity: "info"|"success"|"error" }>({ open: false, message: "", severity: "info" });

  const qs = useMemo(() => new URLSearchParams(location.search), [location.search]);

  const fetchStatus = async (sid: string) => {
    try {
      setErrorMsg(null);
      const url = `${API_BASE.replace(/\/$/, "")}/api/kyc/status?session_id=${encodeURIComponent(sid)}`;
      const res = await fetch(url, { headers: { "Content-Type": "application/json" } });
      const data = await res.json();
      const s = (data?.status || "Pending").toString();
      const normalized: KycState = ["Approved","Rejected","Cancelled","Pending"].includes(s) ? (s as KycState) : "Unknown";
      setStatus(normalized);
    } catch (e: any) {
      setErrorMsg(e?.message || "Failed to fetch KYC status");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const sid = (qs.get("session_id") || localStorage.getItem("didit_session_id") || "").toString();
    if (sid) {
      setSessionId(sid);
      fetchStatus(sid);
    } else {
      setLoading(false);
      setStatus("Unknown");
      setErrorMsg("Missing session identifier.");
    }
    return () => { if (timer.current) window.clearTimeout(timer.current); };
  }, [qs]);

  useEffect(() => {
    if (!sessionId) return;
    if (status === "Pending" || status === "Unknown") {
      // Per requirement: navigate to login while KYC is in progress
      navigate("/", { replace: true, state: { notice: "Your KYC is in progress. Please wait a few minutes or reach out to support@intelliwealth.co.uk.", severity: "info" } });
      // Keep polling in the background if user comes back
      timer.current = window.setTimeout(() => fetchStatus(sessionId), 5000) as any;
    }
  }, [status, sessionId]);

  useEffect(() => {
    if (!sessionId) return;
    if (status === "Approved") {
      if (isLoggedIn) {
        setSnack({ open: true, message: "Please wait 2–3 mins. You will be redirected to the dashboard.", severity: "success" });
        window.setTimeout(() => navigate("/dashboard", { replace: true }), 3000);
      } else {
        navigate("/", { replace: true, state: { notice: "Your KYC is approved. Please log in to continue.", severity: "success" } });
      }
    }
    if (status === "Rejected" || status === "Cancelled") {
      navigate("/", { replace: true, state: { notice: "Your KYC was declined. Please contact support@intelliwealth.co.uk or try again.", severity: "error" } });
    }
  }, [status, isLoggedIn, navigate, sessionId]);

  const tryAgain = () => navigate("/didit-verification", { replace: false });
  const goLogin = () => navigate("/", { replace: true });

  const renderContent = () => {
    if (loading) return <Stack alignItems="center"><CircularProgress /></Stack>;

    if (status === "Approved") {
      return (
        <>
          <Alert severity="success">Your KYC is approved.</Alert>
          {!isLoggedIn && (
            <Button variant="contained" onClick={goLogin}>Login to continue</Button>
          )}
        </>
      );
    }

    if (status === "Rejected") {
      return (
        <>
          <Alert severity="error">Your KYC was declined.</Alert>
          <Stack direction="row" spacing={2}>
            <Button variant="contained" onClick={tryAgain}>Try Again</Button>
            <Button variant="outlined" onClick={() => window.open("mailto:support@intelliwealth.co.uk","_blank")}>Contact Support</Button>
          </Stack>
        </>
      );
    }

    if (status === "Cancelled") {
      return (
        <>
          <Alert severity="warning">KYC session was cancelled or expired.</Alert>
          <Stack direction="row" spacing={2}>
            <Button variant="contained" onClick={tryAgain}>Try Again</Button>
            <Button variant="outlined" onClick={() => window.open("mailto:support@intelliwealth.co.uk","_blank")}>Contact Support</Button>
          </Stack>
        </>
      );
    }

    // Pending/Unknown
    return (
      <>
        <Alert severity="info">KYC is in progress or under review. This page will refresh automatically.</Alert>
        <Stack direction="row" spacing={2}>
          <Button variant="outlined" onClick={() => sessionId && fetchStatus(sessionId)}>Refresh</Button>
          <Button variant="text" onClick={() => window.open("mailto:support@intelliwealth.co.uk","_blank")}>Contact Support</Button>
        </Stack>
      </>
    );
  };

  return (
    <Box sx={{ minHeight: "70vh", display: "flex", alignItems: "center", justifyContent: "center", p: 2 }}>
      <Card sx={{ width: "100%", maxWidth: 720 }}>
        <CardHeader title={<Typography variant="h5">KYC Status</Typography>} subheader={sessionId ? `Session: ${sessionId}` : undefined} />
        <CardContent>
          <Stack spacing={2}>
            {errorMsg && <Alert severity="error">{errorMsg}</Alert>}
            {renderContent()}
          </Stack>
        </CardContent>
      </Card>
      <Snackbar
        open={snack.open}
        autoHideDuration={2500}
        onClose={() => setSnack(s => ({ ...s, open: false }))}
        message={snack.message}
      />
    </Box>
  );
};

export default KycStatus;

