import React, { useEffect, useState } from "react";
import { Alert, Box, Button, LinearProgress, Paper, Skeleton, Stack, Typography } from "@mui/material";
import { api } from "../api";
import { useI18n } from "../i18n/I18nProvider";

type Usage = {
  currentMonth: { calls: number; estimatedTokens: number };
  plan: string;
  monthlyCallLimit: number;
  monthlyTokenLimit: number;
  storageUsedBytes: number;
  storageLimitBytes: number;
};

type BillingStatus = { enabled: boolean; canCheckout: boolean; canManage: boolean };

function formatBytes(bytes: number) {
  if (bytes < 1_000_000) return `${Math.round(bytes / 1_000)} KB`;
  if (bytes < 1_000_000_000) return `${(bytes / 1_000_000).toFixed(1)} MB`;
  return `${(bytes / 1_000_000_000).toFixed(1)} GB`;
}

export default function AiUsageCard() {
  const { t } = useI18n();
  const [usage, setUsage] = useState<Usage | null>(null);
  const [billing, setBilling] = useState<BillingStatus | null>(null);
  const [billingBusy, setBillingBusy] = useState(false);
  const [billingFailed, setBillingFailed] = useState(false);
  const [failed, setFailed] = useState(false);

  useEffect(() => {
    let active = true;
    api.get<Usage>("/ai/usage")
      .then((response) => { if (active) setUsage(response.data); })
      .catch(() => { if (active) setFailed(true); });
    api.get<BillingStatus>("/billing/status")
      .then((response) => { if (active) setBilling(response.data); })
      .catch(() => { /* Billing is optional; usage remains available. */ });
    return () => { active = false; };
  }, []);

  const openBilling = async (path: "checkout" | "portal") => {
    setBillingBusy(true);
    setBillingFailed(false);
    try {
      const response = await api.post<{ url: string }>(`/billing/${path}`);
      window.location.assign(response.data.url);
    } catch {
      setBillingFailed(true);
      setBillingBusy(false);
    }
  };

  if (failed) return <Alert severity="warning">{t("settingsUsageUnavailable")}</Alert>;
  if (!usage) return <Skeleton variant="rounded" height={150} />;

  const callsPercent = usage.monthlyCallLimit > 0 ? Math.min(100, usage.currentMonth.calls / usage.monthlyCallLimit * 100) : 0;
  const tokensPercent = usage.monthlyTokenLimit > 0 ? Math.min(100, usage.currentMonth.estimatedTokens / usage.monthlyTokenLimit * 100) : 0;
  const storagePercent = Math.min(100, usage.storageUsedBytes / usage.storageLimitBytes * 100);

  return (
    <Paper sx={{ p: 2.5, borderRadius: 4, border: "none" }}>
      <Stack direction="row" justifyContent="space-between" alignItems="baseline" sx={{ mb: 2 }}>
        <Typography variant="overline" sx={{ color: "text.secondary", fontWeight: 800 }}>{t("settingsUsageTitle")}</Typography>
        <Typography variant="caption" sx={{ textTransform: "capitalize", fontWeight: 700 }}>{t("settingsUsagePlan", { plan: usage.plan })}</Typography>
      </Stack>
      {usage.monthlyCallLimit === 0 ? <Alert severity="info" sx={{ mb: 2 }}>{t("settingsUsageNoAi")}</Alert> : <><Box sx={{ mb: 2 }}>
        <Typography variant="body2">{t("settingsUsageGenerations", { used: usage.currentMonth.calls.toLocaleString(), limit: usage.monthlyCallLimit.toLocaleString() })}</Typography>
        <LinearProgress variant="determinate" value={callsPercent} aria-label={t("settingsUsageGenerationsProgress")} sx={{ mt: 0.75, height: 7, borderRadius: 99 }} />
      </Box>
      <Box>
        <Typography variant="body2">{t("settingsUsageTokens", { used: usage.currentMonth.estimatedTokens.toLocaleString(), limit: usage.monthlyTokenLimit.toLocaleString() })}</Typography>
        <LinearProgress variant="determinate" value={tokensPercent} aria-label={t("settingsUsageTokensProgress")} sx={{ mt: 0.75, height: 7, borderRadius: 99 }} />
      </Box></>}
      <Box sx={{ mt: 2 }}>
        <Typography variant="body2">{t("settingsUsageStorage", { used: formatBytes(usage.storageUsedBytes), limit: formatBytes(usage.storageLimitBytes) })}</Typography>
        <LinearProgress variant="determinate" value={storagePercent} aria-label={t("settingsUsageStorageProgress")} sx={{ mt: 0.75, height: 7, borderRadius: 99 }} />
      </Box>
      <Typography variant="caption" color="text.secondary" sx={{ display: "block", mt: 1.5 }}>{t("settingsUsageReset")}</Typography>
      {billing?.canCheckout ? <Button sx={{ mt: 2 }} variant="contained" disabled={billingBusy} onClick={() => void openBilling("checkout")}>{t("settingsBillingUpgrade")}</Button> : null}
      {billing?.canManage ? <Button sx={{ mt: 2 }} variant="outlined" disabled={billingBusy} onClick={() => void openBilling("portal")}>{t("settingsBillingManage")}</Button> : null}
      {billingFailed ? <Alert severity="error" sx={{ mt: 2 }}>{t("settingsBillingUnavailable")}</Alert> : null}
      {usage.plan === "free" && billing?.enabled === false ? (
        <Typography variant="caption" sx={{ color: "text.secondary", display: "block", mt: 1.5 }}>
          {t("settingsBillingNotConfigured")}
        </Typography>
      ) : null}
    </Paper>
  );
}
