import React, { 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";

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

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

export default function AiSectionAssistant({ sectionName, text, context, onApply }: Props) {
  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 run = async () => {
    if (!text.trim() || !canUseAi) return;
    setBusy(true);
    try {
      const response = await cvBuilderApi.aiAssist({
        action,
        text,
        context: [`Section: ${sectionName}. Preserve facts and do not invent achievements.`, context].filter(Boolean).join("\n"),
      });
      setSuggestion(response.result);
    } catch (error) {
      toast(getApiErrorMessage(error, "AI suggestion failed."), "error");
    } finally {
      setBusy(false);
    }
  };

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

  if (!canUseAi) {
    return (
      <Stack spacing={1}>
        <ProFeatureNotice featureKey="cv-writing-ai" title="Refine this section with Pro.">
          AI only proposes wording; it never changes CV content without your approval.
        </ProFeatureNotice>
        <Button size="small" onClick={() => setOpen(false)}>Close</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="AI action" 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}>{item.label}</MenuItem>)}
          </TextField>
          <Button size="small" variant="contained" disabled={busy || !text.trim()} onClick={() => void run()}>{busy ? "Working…" : "Suggest"}</Button>
          <Button size="small" onClick={() => { setOpen(false); setSuggestion(""); }}>Close</Button>
        </Stack>
        {suggestion && <>
          <Box>
            <Typography variant="overline" color="text.secondary">Current</Typography>
            <Typography variant="body2" sx={{ whiteSpace: "pre-wrap" }}>{text}</Typography>
          </Box>
          <TextField label="Suggested — edit before applying" multiline minRows={3} fullWidth size="small" value={suggestion} onChange={(event) => setSuggestion(event.target.value)} />
          <Alert severity="info" sx={{ py: 0 }}>Check every fact before applying this suggestion.</Alert>
          <Stack direction="row" spacing={1}>
            <Button size="small" variant="contained" onClick={() => { onApply(suggestion); setSuggestion(""); setOpen(false); toast(`Suggestion applied to ${sectionName}.`, "success"); }}>Apply</Button>
            <Button size="small" onClick={() => setSuggestion("")}>Reject</Button>
          </Stack>
        </>}
      </Stack>
    </Paper>
  );
}
