import React, { useEffect, useState } from "react";

import AutoFixHighIcon from "@mui/icons-material/AutoFixHigh";
import { Alert, Box, Button, MenuItem, Paper, Stack, TextField, Typography } from "@mui/material";

import { getApiErrorMessage } from "../../api";
import { useAccountPlan } from "../../accountPlan";
import { AI_ACTIONS, cvBuilderApi } from "../../cvBuilder";
import { useToast } from "../../toast";
import ProFeatureNotice from "../ProFeatureNotice";
import { useI18n } from "../../i18n/I18nProvider";

type Props = {
  sectionName: string;
  text: string;
  context?: string;
  documentLanguage?: string | null;
  onApply: (suggestion: string) => void;
};

const SECTION_ACTIONS = new Set(["improve", "professional", "shorten", "grammar", "impact", "bullets"]);

export default function AiSectionAssistant({ sectionName, text, context, documentLanguage, onApply }: Props) {
  const { t } = useI18n();
  const { toast } = useToast();
  const { canUseAi } = useAccountPlan();
  const [open, setOpen] = useState(false);
  const [action, setAction] = useState("improve");
  const [suggestion, setSuggestion] = useState("");
  const [busy, setBusy] = useState(false);
  const normalizedLanguage = documentLanguage === "no" || documentLanguage === "nb" ? "nb-NO" : documentLanguage ?? "en";
  const [targetLanguage, setTargetLanguage] = useState(normalizedLanguage);

  useEffect(() => setTargetLanguage(normalizedLanguage), [normalizedLanguage]);

  const run = async () => {
    if (!text.trim() || !canUseAi) return;
    setBusy(true);
    try {
      const response = await cvBuilderApi.aiAssist({
        action,
        text,
        language: targetLanguage,
        context: [`Section: ${sectionName}. Preserve facts and do not invent achievements.`, context].filter(Boolean).join("\n"),
      });
      setSuggestion(response.result);
    } catch (error) {
      toast(getApiErrorMessage(error, t("cvAiFailed")), "error");
    } finally {
      setBusy(false);
    }
  };

  if (!open) {
    return (
      <Button size="small" variant="outlined" startIcon={<AutoFixHighIcon />} disabled={!text.trim()} onClick={() => setOpen(true)}>
        {t("cvAiSuggestions")}
      </Button>
    );
  }

  if (!canUseAi) {
    return (
      <Stack spacing={1}>
        <ProFeatureNotice featureKey="cv-writing-ai" title={t("cvAiProTitle")}>
          {t("cvAiProBody")}
        </ProFeatureNotice>
        <Button size="small" onClick={() => setOpen(false)}>{t("cvAiClose")}</Button>
      </Stack>
    );
  }

  return (
    <Paper variant="outlined" sx={{ p: 1.25, borderColor: "primary.main", bgcolor: "action.hover" }}>
      <Stack spacing={1}>
        <Stack direction={{ xs: "column", sm: "row" }} spacing={1} alignItems={{ sm: "center" }}>
          <TextField select size="small" label={t("cvAiAction")} value={action} onChange={(event) => setAction(event.target.value)} sx={{ minWidth: 190 }}>
            {AI_ACTIONS.filter((item) => SECTION_ACTIONS.has(item.key)).map((item) => <MenuItem key={item.key} value={item.key}>{actionLabel(item.key, item.label, t)}</MenuItem>)}
          </TextField>
          <TextField select size="small" label={t("cvAiLanguage")} value={targetLanguage} onChange={(event) => setTargetLanguage(event.target.value)} sx={{ minWidth: 150 }}>
            <MenuItem value="en">{t("languageEnglish")}</MenuItem>
            <MenuItem value="nb-NO">{t("languageNorwegianBokmal")}</MenuItem>
          </TextField>
          <Button size="small" variant="contained" disabled={busy || !text.trim()} onClick={() => void run()}>{busy ? t("cvAiWorking") : t("cvAiSuggest")}</Button>
          <Button size="small" onClick={() => { setOpen(false); setSuggestion(""); }}>{t("cvAiClose")}</Button>
        </Stack>
        {suggestion && <>
          <Box>
            <Typography variant="overline" color="text.secondary">{t("cvAiCurrent")}</Typography>
            <Typography variant="body2" sx={{ whiteSpace: "pre-wrap" }}>{text}</Typography>
          </Box>
          <TextField label={t("cvAiSuggested")} multiline minRows={3} fullWidth size="small" value={suggestion} onChange={(event) => setSuggestion(event.target.value)} />
          <Alert severity="info" sx={{ py: 0 }}>{t("cvAiCheckFacts")}</Alert>
          <Stack direction="row" spacing={1}>
            <Button size="small" variant="contained" onClick={() => { onApply(suggestion); setSuggestion(""); setOpen(false); toast(t("cvAiApplied", { section: sectionName }), "success"); }}>{t("cvAiApply")}</Button>
            <Button size="small" onClick={() => setSuggestion("")}>{t("cvAiReject")}</Button>
          </Stack>
        </>}
      </Stack>
    </Paper>
  );
}

type Translate = ReturnType<typeof useI18n>["t"];

function actionLabel(key: string, fallback: string, t: Translate) {
  const labels: Record<string, string> = {
    improve: t("cvAiImprove"), professional: t("cvAiProfessional"), shorten: t("cvAiShorten"),
    grammar: t("cvAiGrammar"), impact: t("cvAiImpact"), bullets: t("cvAiBullets"),
  };
  return labels[key] ?? fallback;
}
