"use client";

import { useState, useEffect } from "react";
import axios from "axios";
import PageContainer from "../../app/components/container/PageContainer";
import BaseCard from "../../app/components/shared/BaseCard";
import {
  Button,
  Grid,
  Typography,
  TextField,
  Alert,
  Radio,
  RadioGroup,
  FormControlLabel,
  LinearProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Box
} from "@mui/material";
import { getSession } from "../../utils/sessionData";

import dayjs from "dayjs";
import { LocalizationProvider } from "@mui/x-date-pickers";
import { MobileDatePicker } from "@mui/x-date-pickers/MobileDatePicker";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import CustomTextField from "../components/forms/theme-elements/CustomTextField";

// ---- ICONS ---- //
const BankIcon = () => (
  <svg width="28" height="28" fill="#1976d2" viewBox="0 0 24 24">
    <path d="M12 2 2 7v2h20V7L12 2zm-7 9v7h2v-7H5zm4 0v7h2v-7H9zm4 0v7h2v-7h-2zm4 0v7h2v-7h-2zM4 20h16v2H4v-2z" />
  </svg>
);

const PlusIcon = () => (
  <svg width="24" height="24" fill="#1976d2" viewBox="0 0 24 24">
    <path d="M19 13H13V19H11V13H5V11H11V5H13V11H19V13Z" />
  </svg>
);

export default function CashoutPage() {
  const [sessionData, setSessionData] = useState<any>();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  const [accounts, setAccounts] = useState<any[]>([]);
  const [user, setUser] = useState<any>();
  const [selected, setSelected] = useState<"bank" | "paypal" | "venmo">("bank");

  const [selectedBank, setSelectedBank] = useState<any>(null);
  const [amount, setAmount] = useState("");
  const [payoutMethods, setPayoutMethods] = useState<any[]>([]);
  // CoinFlow KYC modal (default)
  const [openCoinFlowModal, setOpenCoinFlowModal] = useState(false);
  const [form, setForm] = useState({
    physicalAddress: "",
    city: "",
    state: "",
    zip: "",
    dob: "",
    ssn: ""
  });
  const isGlobalEnabled = (methodKey: string) => {
    const method = payoutMethods.find((m) => m.method === methodKey);
    return method?.status == 1;
  };
  // PayPal / Venmo phone modal
  const [openPayVenmoModal, setOpenPayVenmoModal] = useState(false);
  const [payVenmoMode, setPayVenmoMode] = useState<"paypal" | "venmo" | null>(
    null
  );
  const [payVenmoPhone, setPayVenmoPhone] = useState("");
  const getPayoutMethods = async () => {
    try {
      const response = await axios.post("/api/payoutMethods", {
        token: sessionData?.token
      });

      if (response.data.status === "error") {
        throw new Error(response.data.message);
      }

      setPayoutMethods(response.data.payoutMethods || []);
    } catch (err: any) {
      setError(err.message || "Unable to load payout methods");
    }
  };
  // Fetch session
  useEffect(() => {
    const session = getSession();
    setSessionData(session);
  }, []);

  // Auto-clear alerts
  useEffect(() => {
    if (error || success) {
      const t = setTimeout(() => {
        setError(null);
        setSuccess(null);
      }, 3000);
      return () => clearTimeout(t);
    }
  }, [error, success]);

  // Fetch Admin (for cfAccount, cfPaypalToken, cfVenmoToken, etc.)
  const getAdmin = async () => {
    try {
      const token = sessionData?.token ?? "";
      const response = await axios.post("/api/getAdmin", { token });

      if (response.data.status === "error") throw new Error(response.data.message);

      setUser(response.data.admin);
    } catch (err: any) {
      setError(err.message ?? "Unable to fetch admin");
    }
  };

  useEffect(() => {
    if (sessionData?.token) {
      getAdmin();
      getPayoutMethods();
    }
  }, [sessionData?.token, sessionData?.admin_id]);

  // Fetch Bank Accounts
  useEffect(() => {
    if (!sessionData?.token) return;

    const fetchAccounts = async () => {
      setLoading(true);
      try {
        const response = await axios.post("/api/getCFBankAccounts", {
          token: sessionData.token,
          userid: sessionData?.admin_id
        });

        if (response.data.status === "error") throw new Error(response.data.message);

        setAccounts(response.data.accounts || []);
      } catch (err: any) {
        setError(err.message || "Unable to load accounts");
      }
      setLoading(false);
    };

    fetchAccounts();
  }, [sessionData]);

  // Clear selected bank if user switches method
  useEffect(() => {
    if (selected !== "bank") {
      setSelectedBank(null);
    }
  }, [selected]);

  const hasCfAccount = user?.cfAccount == "1";
  const showBank =
    // hasCfAccount &&
    isGlobalEnabled("coinflow") &&
    user?.cfAccountAllowed == 1;

  const showPaypal =
    isGlobalEnabled("coinflow_paypal") &&
    user?.cfPaypalAllowed == 1;

  const showVenmo =
    isGlobalEnabled("coinflow_venmo") &&
    user?.cfVenmoAllowed == 1;

  const isLinked =
    (selected === "bank" && selectedBank !== null) ||
    (selected === "paypal" && !!user?.cfPaypalToken) ||
    (selected === "venmo" && !!user?.cfVenmoToken);

  // Withdraw
  const handleWithdraw = async () => {
    if (!amount) {
      setError("Enter a valid amount");
      return;
    }

    if (selected === "bank" && !selectedBank) {
      setError("Please select a bank account");
      return;
    }

    setLoading(true);
    console.log(selectedBank)
    try {
      const response = await axios.post("/api/requestWithdraw", {
        token: sessionData?.token,
        type: selected,
        amount,
        acToken: selectedBank?.token || null
      });

      if (response.data.status == "error") {
        setError(response?.data?.message)
        // throw new Error(response.data.message);
      }
      else {
        setSuccess("Withdrawal request submitted!");
        setAmount("");
      }
    } catch (err: any) {
      setError(err.message || "Withdrawal failed");
    }

    setLoading(false);
  };

  // Redirect to CoinFlow to manage/add bank when cfAccount = 1
  const redirectToCoinFlow = async () => {
    try {
      setLoading(true);
      const response = await axios.post("/api/getCoinFlowRedirectUrl", {
        token: sessionData?.token,
        userId: sessionData?.admin_id,
        site: `${window.location.origin}/linkaccount`
      });

      if (response.data.status === "error") {
        throw new Error(response.data.message);
      }

      const redirectUrl =
        response.data.redirectUrl ||
        response.data.url ||
        response.data.redirect ||
        `${window.location.origin}/linkaccount`;

      window.location.href = redirectUrl;
    } catch (err: any) {
      setError(err.message || "Unable to redirect to CoinFlow");
    } finally {
      setLoading(false);
    }
  };

  // Main "Link" action per method
  // const handleLink = async () => {
  //   // If user is NOT yet CoinFlow onboarded => show KYC dialog for all methods
  //   if (!hasCfAccount) {
  //     setOpenCoinFlowModal(true);
  //     return;
  //   }

  //   // If user already has CoinFlow account
  //   if (selected === "bank") {
  //     await redirectToCoinFlow();
  //   } else if (selected === "paypal") {
  //     setPayVenmoMode("paypal");
  //     setPayVenmoPhone("");
  //     setOpenPayVenmoModal(true);
  //   } else if (selected === "venmo") {
  //     setPayVenmoMode("venmo");
  //     setPayVenmoPhone("");
  //     setOpenPayVenmoModal(true);
  //   }
  // };
  const handleLink = async () => {
    console.log("HANDLE LINK CALLED", {
      hasCfAccount,
      selected
    });

    if (!hasCfAccount) {
      console.log("OPENING COINFLOW MODAL");
      setOpenCoinFlowModal(true);
      return;
    }

    if (selected === "paypal") {
      console.log("OPENING PAYPAL MODAL");
      setPayVenmoMode("paypal");
      setOpenPayVenmoModal(true);
    }

    if (selected === "venmo") {
      console.log("OPENING VENMO MODAL");
      setPayVenmoMode("venmo");
      setOpenPayVenmoModal(true);
    }
  };
  // Add new bank card click
  const handleAddBankClick = async () => {
    if (!hasCfAccount) {
      setOpenCoinFlowModal(true);
      return;
    }
    await redirectToCoinFlow();
  };

  const handleSavePayVenmo = async () => {
    if (!payVenmoPhone) {
      setError("Please enter phone number");
      return;
    }

    if (!payVenmoMode) return;

    setLoading(true);

    try {
      const endpoint =
        payVenmoMode === "paypal"
          ? "/api/registerPaypalToken"
          : "/api/registerVenmoToken";

      const response = await axios.post(endpoint, {
        token: sessionData?.token,
        userId: sessionData?.admin_id,
        [payVenmoMode === "paypal" ? "paypal" : "venmo"]: payVenmoPhone
      });

      if (response.data.status === "error") {
        throw new Error(response.data.message);
      }

      setSuccess(
        payVenmoMode === "paypal"
          ? "PayPal linked successfully!"
          : "Venmo linked successfully!"
      );
      setOpenPayVenmoModal(false);
      setPayVenmoPhone("");
      // Refresh user to get cfPaypalToken / cfVenmoToken
      getAdmin();
    } catch (err: any) {
      setError(err.message || "Failed to link account");
    } finally {
      setLoading(false);
    }
  };

  return (
    <PageContainer title="Cashout" description="Select withdrawal method">
      <Grid container spacing={3}>
        <Grid sx={{ width: { lg: "50%", xs: "100%" } }}>

          {error && <Alert severity="error">{error}</Alert>}
          {success && <Alert severity="success">{success}</Alert>}
        </Grid>

        <Grid sx={{ width: { lg: "50%", xs: "100%" } }}>
          <BaseCard title={user ? `Cashout - Balance ($${user?.balance})` : `Cashout`}>
            {loading && (
              <>
                <LinearProgress />
                <br />
              </>
            )}

            <Typography variant="subtitle2" sx={{ mb: 2, fontWeight: 600 }}>
              Select Withdrawal Method
            </Typography>

            {/* Withdrawal Method */}
            {/* <RadioGroup
              value={selected}
              onChange={(e) =>
                setSelected(e.target.value as "bank" | "paypal" | "venmo")
              }
              sx={{ mb: 3 }}
            >
              <FormControlLabel
                value="bank"
                control={<Radio />}
                label="Bank Transfer"
              />
              <FormControlLabel value="paypal" control={<Radio />} label="PayPal" />
              <FormControlLabel value="venmo" control={<Radio />} label="Venmo" />
            </RadioGroup> */}
            <RadioGroup
              value={selected}
              onChange={(e) =>
                setSelected(e.target.value as "bank" | "paypal" | "venmo")
              }
              sx={{ mb: 3 }}
            >
              {showBank && (
                <FormControlLabel
                  value="bank"
                  control={<Radio />}
                  label="Bank Transfer"
                />
              )}

              {showPaypal && (
                <FormControlLabel
                  value="paypal"
                  control={<Radio />}
                  label="PayPal"
                />
              )}

              {showVenmo && (
                <FormControlLabel
                  value="venmo"
                  control={<Radio />}
                  label="Venmo"
                />
              )}
            </RadioGroup>
            {/* BANK ACCOUNT LIST */}
            {loading && (
              <>
                <Typography variant="subtitle2" sx={{ fontWeight: 600, mb: 1 }}>
                  Loading Accounts...
                </Typography>
                <br />
              </>
            )}
            {selected === "bank" && accounts.length > 0 && (
              <Box sx={{ mb: 3 }}>
                <Typography variant="subtitle2" sx={{ fontWeight: 600, mb: 1 }}>
                  Select Bank Account
                </Typography>

                <Grid container spacing={2}>
                  {accounts.map((acc: any) => (
                    <Grid sx={{ width: "100%" }} key={acc.id}>
                      <Box
                        onClick={() => setSelectedBank(acc)}
                        sx={{ display: "flex", alignItems: "center", gap: 2, p: 2, borderRadius: "10px", border: selectedBank?.id === acc.id ? "2px solid #1976d2" : "2px solid #e0e0e0", cursor: "pointer", transition: "0.2s", "&:hover": { borderColor: "#1976d2" } }}
                      >
                        <BankIcon />
                        <Box>
                          <Typography sx={{ fontWeight: 600 }}>{acc.alias}</Typography>
                          <Typography variant="body2" sx={{ color: "gray" }}>
                            **** {acc.last4}
                          </Typography>
                        </Box>
                      </Box>
                    </Grid>
                  ))}

                  {/* ADD NEW ACCOUNT BUTTON */}
                  <Grid sx={{ width: "100%" }}>
                    <Box
                      onClick={handleAddBankClick}
                      sx={{
                        display: "flex",
                        alignItems: "center",
                        gap: 2,
                        p: 2,
                        borderRadius: "10px",
                        border: "2px dashed #9e9e9e",
                        cursor: "pointer",
                        color: "#616161",
                        "&:hover": { borderColor: "#1976d2", color: "#1976d2" }
                      }}
                    >
                      <PlusIcon />
                      <Typography sx={{ fontWeight: 600 }}>
                        Add New Bank Account
                      </Typography>
                    </Box>
                  </Grid>
                </Grid>
              </Box>
            )}

            {/* Amount or Link Button */}
            {isLinked ? (
              <>
                <TextField
                  fullWidth
                  type="number"
                  label="Enter Amount"
                  value={amount}
                  onChange={(e) => setAmount(e.target.value)}
                  sx={{ mb: 3 }}
                />

                <Button
                  variant="contained"
                  color="primary"
                  fullWidth
                  onClick={handleWithdraw}
                >
                  Withdraw Now
                </Button>
              </>
            ) : (
              <Button
                variant="contained"
                color="primary"
                fullWidth
                onClick={handleLink}
                disabled={loading}
              >
                {selected === "bank"
                  ? "Select Account"
                  : selected === "paypal"
                    ? "Link PayPal"
                    : "Link Venmo"}
              </Button>
            )}

            {/* ---------- DEFAULT COINFLOW KYC MODAL (cfAccount = 0) ---------- */}
            <Dialog
              open={openCoinFlowModal}
              onClose={() => setOpenCoinFlowModal(false)}
              fullWidth
              maxWidth="xs"
            >
              <DialogTitle>Register CoinFlow</DialogTitle>

              <DialogContent>
                <Grid container spacing={2} sx={{ mt: 1 }}>
                  <Grid sx={{ width: "100%" }}>
                    <TextField
                      fullWidth
                      label="Physical Address"
                      value={form.physicalAddress}
                      onChange={(e) =>
                        setForm({ ...form, physicalAddress: e.target.value })
                      }
                    />
                  </Grid>

                  <Grid sx={{ width: "100%" }}>
                    <TextField
                      fullWidth
                      label="City"
                      value={form.city}
                      onChange={(e) => setForm({ ...form, city: e.target.value })}
                    />
                  </Grid>

                  <Grid sx={{ width: "100%" }}>
                    <TextField
                      fullWidth
                      label="State"
                      inputProps={{ maxLength: 2 }}
                      value={form.state}
                      onChange={(e) => setForm({ ...form, state: e.target.value })}
                    />
                  </Grid>

                  <Grid sx={{ width: "100%" }}>
                    <TextField
                      fullWidth
                      label="Zip Code"
                      inputProps={{ maxLength: 5 }}
                      value={form.zip}
                      onChange={(e) => setForm({ ...form, zip: e.target.value })}
                    />
                  </Grid>

                  <Grid sx={{ width: "100%" }}>
                    {/* <LocalizationProvider dateAdapter={AdapterDayjs}>
                      <MobileDatePicker
                        label="Date of Birth"
                        value={form.dob ? dayjs(form.dob) : null}
                        onChange={(newValue) =>
                          setForm({
                            ...form,
                            dob: newValue
                              ? dayjs(newValue).format("YYYY-MM-DD")
                              : ""
                          })
                        }
                        slots={{ textField: CustomTextField }}
                        slotProps={{
                          textField: {
                            fullWidth: true,
                            size: "small",
                            variant: "outlined"
                          }
                        }}
                      />
                    </LocalizationProvider> */}
                    <LocalizationProvider dateAdapter={AdapterDayjs}>
                      <MobileDatePicker
                        label="Date of Birth"
                        enableAccessibleFieldDOMStructure={false}
                        value={form.dob ? dayjs(form.dob) : null}
                        onChange={(newValue) =>
                          setForm({
                            ...form,
                            dob: newValue
                              ? dayjs(newValue).format("YYYY-MM-DD")
                              : ""
                          })
                        }
                        slots={{ textField: CustomTextField }}
                        slotProps={{
                          textField: {
                            fullWidth: true,
                            size: "small",
                            variant: "outlined"
                          }
                        }}
                      />
                    </LocalizationProvider>
                  </Grid>

                  <Grid sx={{ width: "100%" }}>
                    <TextField
                      fullWidth
                      label="SSN (Last 4 Digits)"
                      inputProps={{ maxLength: 4 }}

                      value={form.ssn}
                      onChange={(e) => setForm({ ...form, ssn: e.target.value })}
                    />
                  </Grid>
                </Grid>
              </DialogContent>

              <DialogActions>
                <Button onClick={() => setOpenCoinFlowModal(false)}>Cancel</Button>
                <Button
                  variant="contained"
                  onClick={async () => {
                    try {
                      setLoading(true);

                      const registerResponse = await axios.post(
                        "/api/registerCoinFlowUser",
                        {
                          token: sessionData?.token,
                          userId: sessionData?.admin_id,
                          physicalAddress: form.physicalAddress,
                          city: form.city,
                          state: form.state,
                          zip: form.zip,
                          dob: form.dob,
                          ssn: form.ssn
                        }
                      );

                      const res = registerResponse.data;

                      if (res.status !== "success") {
                        throw new Error(res.message || "Registration failed");
                      }

                      if (
                        res.message === "CoinFlow Registration Successful" ||
                        res.message === "KYC already exists"
                      ) {
                        setOpenCoinFlowModal(false);
                        await redirectToCoinFlow();
                        return;
                      }

                      throw new Error("Unexpected CoinFlow response");
                    } catch (err: any) {
                      setError(
                        err.message || "Unable to complete CoinFlow onboarding"
                      );
                    } finally {
                      setLoading(false);
                    }
                  }}
                >
                  Save & Continue
                </Button>
              </DialogActions>
            </Dialog>

            {/* ---------- PAYPAL / VENMO PHONE MODAL (cfAccount = 1) ---------- */}
            <Dialog
              open={openPayVenmoModal}
              onClose={() => setOpenPayVenmoModal(false)}
              fullWidth
              maxWidth="xs"
            >
              <DialogTitle>
                {payVenmoMode === "paypal"
                  ? "Link PayPal Account"
                  : "Link Venmo Account"}
              </DialogTitle>

              <DialogContent>
                <Grid container spacing={2} sx={{ mt: 1 }}>
                  <Grid sx={{ width: "100%" }}>
                    <TextField
                      fullWidth
                      label={
                        payVenmoMode === "paypal"
                          ? "PayPal Phone Number"
                          : "Venmo Phone Number"
                      }
                      value={payVenmoPhone}
                      onChange={(e) => setPayVenmoPhone(e.target.value)}
                    />
                  </Grid>
                </Grid>
              </DialogContent>

              <DialogActions>
                <Button onClick={() => setOpenPayVenmoModal(false)}>Cancel</Button>
                <Button variant="contained" onClick={handleSavePayVenmo}>
                  Save & Continue
                </Button>
              </DialogActions>
            </Dialog>
          </BaseCard>
        </Grid>
      </Grid>
    </PageContainer>
  );
}
