import React, { useEffect, useMemo, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import {
  Box,
  Card,
  CardHeader,
  CardContent,
  Typography,
  Button,
  TextField,
  Checkbox,
  FormControlLabel,
  Stack,
  Alert,
  IconButton,
  CircularProgress,
} from "@mui/material";
import ContentCopyIcon from "@mui/icons-material/ContentCopy";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
import OpenInNewIcon from "@mui/icons-material/OpenInNew";
import { useSession } from "../../context/sessioncontext";

type Props = {
  apiPath?: string;
  callbackPath?: string; 
  defaultIframe?: boolean;
  workflowId?: string;
};

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

const DEFAULT_API = `${API_BASE.replace(/\/$/, "")}/api/didit/verification-sessions`;

const ENV_WORKFLOW_ID =
  (import.meta as any)?.env?.VITE_VERIFICATION_WORKFLOW_ID ||
  (process.env as any)?.REACT_APP_DIDIT_WORKFLOW_ID ||
  "";

const DiditVerification: React.FC<Props> = ({
  apiPath = DEFAULT_API,
  callbackPath = "/verification-callback",
  defaultIframe = true,
}) => {
  const navigate = useNavigate();
  const iframeRef = useRef<HTMLIFrameElement | null>(null);

  const [verificationUrl, setVerificationUrl] = useState<string>("");
  const [email, setEmail] = useState<string>("");
  const [sessionId, setSessionId] = useState<string>("");
  const [isIframe, setIsIframe] = useState<boolean>(defaultIframe);
  const [loading, setLoading] = useState<boolean>(false);
  const [copied, setCopied] = useState<boolean>(false);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const { isLoggedIn } = useSession();
  const [iframeLoading, setIframeLoading] = useState<boolean>(false);
  const apiOk = useMemo(() => Boolean(API_BASE && (API_BASE as string).startsWith("http")), []);

  const createVerificationSession = async () => {
    setLoading(true);
    setErrorMsg(null);
    setVerificationUrl("");

    try {
      const wfId = process.env.REACT_APP_VERIFICATION_WORKFLOW_ID
      if (!wfId) {
        throw new Error(
          "Missing workflowId. Set VITE_VERIFICATION_WORKFLOW_ID (Vite) or REACT_APP_VERIFICATION_WORKFLOW_ID (CRA), or pass workflowId prop."
        );
      }

      const redirectUri = `${window.location.origin}${callbackPath}`;
      let vendorEmail: string | undefined;
      try {
        const raw = localStorage.getItem("user");
        if (raw) {
          const u = JSON.parse(raw);
          if (u && typeof u.email === "string" && u.email.includes("@")) {
            vendorEmail = u.email;
            if (vendorEmail) setEmail(vendorEmail);
          }
        }
      } catch {}

      const res = await fetch(apiPath, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ isIframe, redirectUri, workflowId: wfId, email: vendorEmail }),
      });

      if (!res.ok) {
        const text = await res.text();
        throw new Error(text || `HTTP ${res.status}`);
      }

      const data = await res.json();
      if (data?.session_id) {
        const sid = String(data.session_id);
        setSessionId(sid);
        try { localStorage.setItem("didit_session_id", sid); } catch {}
      }
      if (data?.url) {
        setVerificationUrl(data.url as string);
        if (isIframe) setIframeLoading(true);
      } else {
        throw new Error("Verification URL not returned by API");
      }
    } catch (e: any) {

      console.error(e);
      setErrorMsg(e?.message || "Failed to create verification session");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    try { if (window.innerWidth < 768) setIsIframe(false); } catch {}
    createVerificationSession();
  }, []);

  // Fallback: poll KYC status while user is on this page, navigate when Approved/terminal
  useEffect(() => {
    if (!sessionId) return;
    let cancelled = false;
    const api = `${API_BASE.replace(/\/$/, "")}/api/kyc/status?session_id=${encodeURIComponent(sessionId)}`;
    const poll = async () => {
      try {
        const res = await fetch(api);
        const data = await res.json();
        const s = (data?.status || "").toString();
        if (["Approved","Rejected","Cancelled"].includes(s)) {
          if (!cancelled) {
            navigate(`/kyc?session_id=${encodeURIComponent(sessionId)}`, { replace: true });
          }
          return; // stop polling
        }
      } catch {}
      // schedule next check
      if (!cancelled) setTimeout(poll, 4000);
    };
    const t = setTimeout(poll, 4000);
    return () => { cancelled = true; clearTimeout(t); };
  }, [sessionId, navigate]);

  useEffect(() => {
    const onMsg = (event: MessageEvent) => {
      const msg = event.data;
      if (msg && typeof msg === "object" && msg.type === "didit:complete") {
        try {
          const sid = localStorage.getItem("didit_session_id");
          if (sid) navigate(`/kyc?session_id=${encodeURIComponent(sid)}`, { replace: true });
          else navigate(`/kyc`, { replace: true });
        } catch {
          navigate(`/kyc`, { replace: true });
        }
      }
    };
    window.addEventListener("message", onMsg);
    return () => window.removeEventListener("message", onMsg);
  }, [navigate]);

  const onIframeLoad = () => {
    const iframe = iframeRef.current;
    if (!iframe) return;
    try {
      setIframeLoading(false);
      const href = iframe.contentWindow?.location?.href || "";
      if (href.includes(callbackPath) || href.includes("/api/didit/webhooks") || href.includes("/api/webhooks/didit")) {
        const sid = localStorage.getItem("didit_session_id");
        if (sid) navigate(`/kyc?session_id=${encodeURIComponent(sid)}`, { replace: true });
        else navigate(`/kyc`, { replace: true });
      }
    } catch {
     
    }
  };

  const copyToClipboard = async () => {
    try {
      if (verificationUrl) {
        await navigator.clipboard.writeText(verificationUrl);
        setCopied(true);
        setTimeout(() => setCopied(false), 1800);
      }
    } catch {
      // ignore
    }
  };

  return (
    <Box
      sx={{
        minHeight: "80vh",
        bgcolor: "#F9FAFC",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        p: 2,
      }}
    >
      <Card sx={{ width: "100%", maxWidth: 900 }}>
        <CardHeader
          title={<Typography variant="h5">Identity Verification</Typography>}
          subheader="Start your KYC verification. This takes about 2–3 minutes."
        />
        <CardContent>
          <Stack spacing={2}>
            {!apiOk && (
              <Alert severity="warning">
                Configuration: REACT_APP_API_URL_DIDIT is missing or invalid.
              </Alert>
            )}
            {email && (
              <Alert severity="info">Verifying for: <strong>{email}</strong></Alert>
            )}
            <FormControlLabel
              control={
                <Checkbox
                  checked={isIframe}
                  onChange={(e) => setIsIframe(e.target.checked)}
                />
              }
              label="Open inside this page (uncheck to open in a new tab)"
            />

            <Box>
              <Button
                variant="contained"
                onClick={createVerificationSession}
                disabled={loading}
                startIcon={loading ? <CircularProgress size={18} /> : undefined}
              >
                {verificationUrl ? "Restart Verification" : "Start Verification"}
              </Button>
            </Box>

            {errorMsg && <Alert severity="error">{errorMsg}</Alert>}

            {verificationUrl && (
              <Stack spacing={2}>
                <Stack direction={{ xs: "column", sm: "row" }} spacing={1} alignItems={{ xs: "stretch", sm: "center" }}>
                  <TextField
                    fullWidth
                    size="small"
                    label="Verification URL"
                    value={verificationUrl}
                    InputProps={{ readOnly: true }}
                  />
                  <IconButton aria-label="Copy" onClick={copyToClipboard}>
                    {copied ? <CheckCircleIcon color="success" /> : <ContentCopyIcon />}
                  </IconButton>
                  <IconButton
                    aria-label="Open in new tab"
                    onClick={() =>
                      window.open(verificationUrl, "_blank", "noopener,noreferrer")
                    }
                  >
                    <OpenInNewIcon />
                  </IconButton>
                </Stack>

                {!isIframe && (
                  <Alert severity="info">Click the top-right icon to open verification in a new tab.</Alert>
                )}

                {isIframe && (
                  <Box
                    sx={{
                      border: 1,
                      borderColor: "divider",
                      borderRadius: 1,
                      overflow: "hidden",
                      height: { xs: 440, md: 680 },
                      position: "relative",
                    }}
                  >
                    {iframeLoading && (
                      <Box
                        sx={{
                          position: "absolute",
                          inset: 0,
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "center",
                          bgcolor: "rgba(255,255,255,0.6)",
                          zIndex: 1,
                        }}
                      >
                        <Stack spacing={1} alignItems="center">
                          <CircularProgress size={28} />
                          <Typography variant="body2" color="text.secondary">Loading verification…</Typography>
                        </Stack>
                      </Box>
                    )}
                    <iframe
                      ref={iframeRef}
                      src={verificationUrl}
                      title="Didit Verification"
                      style={{ width: "100%", height: "100%", border: 0 }}
                      onLoad={onIframeLoad}
                      allow="fullscreen; camera; microphone; autoplay; encrypted-media"
                      allowFullScreen
                    />
                  </Box>
                )}
                <Typography variant="caption" color="text.secondary">
                  Having trouble? Ensure camera and microphone permissions are allowed. Need help?
                  <Button size="small" onClick={() => window.open("mailto:support@intelliwealth.co.uk","_blank")}>Contact Support</Button>
                </Typography>
              </Stack>
            )}
          </Stack>
        </CardContent>
      </Card>
    </Box>
  );
};

export default DiditVerification;
