import React, { useEffect, useState } from "react";
import PropTypes from "prop-types";
import {
  Box,
  Button,
  Flex,
  SingleSelect,
  SingleSelectOption,
  TextInput,
  Typography,
} from "@strapi/design-system";
import { aiSettingsApi } from "../../utils/api";

const PROVIDERS = [
  { id: "anthropic", label: "Claude (Anthropic)", modelPlaceholder: "claude-sonnet-5" },
  { id: "openai", label: "GPT (OpenAI)", modelPlaceholder: "gpt-4o-mini" },
  { id: "gemini", label: "Gemini (Google)", modelPlaceholder: "gemini-flash-latest" },
];

const emptyForm = () =>
  PROVIDERS.reduce((form, provider) => ({ ...form, [provider.id]: { apiKey: "", model: "" } }), {});

const AISettingsPanel = ({ onClose }) => {
  const [saved, setSaved] = useState(null);
  const [form, setForm] = useState(emptyForm());
  const [defaultProvider, setDefaultProvider] = useState("");
  const [replacingKeys, setReplacingKeys] = useState({});
  const [testResults, setTestResults] = useState({});
  const [notice, setNotice] = useState(null);
  const [isSaving, setIsSaving] = useState(false);

  const handleTest = async (providerId) => {
    setTestResults((current) => ({ ...current, [providerId]: { status: "running" } }));

    try {
      const result = await aiSettingsApi.test(providerId);
      setTestResults((current) => ({
        ...current,
        [providerId]: { status: "ok", text: `Works — answered via ${result.model}` },
      }));
    } catch (error) {
      const detail = error.response?.data?.error ?? error.message ?? "Request failed";
      setTestResults((current) => ({
        ...current,
        [providerId]: { status: "error", text: detail },
      }));
    }
  };

  useEffect(() => {
    aiSettingsApi
      .get()
      .then((settings) => {
        setSaved(settings);
        setDefaultProvider(settings.defaultProvider ?? "");
        setForm(
          PROVIDERS.reduce(
            (next, provider) => ({
              ...next,
              [provider.id]: { apiKey: "", model: settings.providers?.[provider.id]?.model ?? "" },
            }),
            {}
          )
        );
      })
      .catch(() => setNotice({ type: "danger", text: "Failed to load AI settings" }));
  }, []);

  const updateProviderField = (providerId, field, value) =>
    setForm((current) => ({
      ...current,
      [providerId]: { ...current[providerId], [field]: value },
    }));

  const handleClearKey = async (providerId) => {
    const confirmed = window.confirm("Remove the saved API key for this provider?");
    if (!confirmed) return;

    try {
      const next = await aiSettingsApi.update({ providers: { [providerId]: { apiKey: "" } } });
      setSaved(next);
      updateProviderField(providerId, "apiKey", "");
      setReplacingKeys((current) => ({ ...current, [providerId]: false }));
      setNotice({ type: "success", text: "API key removed" });
    } catch (error) {
      setNotice({ type: "danger", text: `Failed to remove key: ${error.message}` });
    }
  };

  const handleSave = async () => {
    setIsSaving(true);
    setNotice(null);

    const providers = {};
    PROVIDERS.forEach(({ id }) => {
      const entry = form[id];
      const patch = { model: entry.model };
      if (entry.apiKey.trim() !== "") patch.apiKey = entry.apiKey.trim();
      providers[id] = patch;
    });

    try {
      const next = await aiSettingsApi.update({ defaultProvider, providers });
      setSaved(next);
      setForm((current) =>
        PROVIDERS.reduce(
          (reset, provider) => ({
            ...reset,
            [provider.id]: { ...current[provider.id], apiKey: "" },
          }),
          {}
        )
      );
      setReplacingKeys({});
      setNotice({ type: "success", text: "AI settings saved — keys are stored encrypted" });
    } catch (error) {
      setNotice({ type: "danger", text: `Failed to save: ${error.message}` });
    } finally {
      setIsSaving(false);
    }
  };

  const renderKeyInput = (provider, savedEntry, entry) => {
    const isReplacing = replacingKeys[provider.id] === true;

    if (savedEntry?.hasKey && !isReplacing) {
      return (
        <Flex gap={2} alignItems="center">
          <Box style={{ flex: 1 }}>
            <TextInput
              name={`ai-key-${provider.id}`}
              value={`••••••••••••${savedEntry.keyHint}`}
              disabled
              aria-label={`${provider.label} saved API key`}
            />
          </Box>
          <Button
            variant="secondary"
            onClick={() => setReplacingKeys((current) => ({ ...current, [provider.id]: true }))}
          >
            Replace key
          </Button>
        </Flex>
      );
    }

    return (
      <Flex gap={2} alignItems="center">
        <Box style={{ flex: 1 }}>
          <TextInput
            name={`ai-key-${provider.id}`}
            type="password"
            value={entry?.apiKey ?? ""}
            onChange={(event) => updateProviderField(provider.id, "apiKey", event.target.value)}
            placeholder="Paste the API key here"
            autoComplete="new-password"
          />
        </Box>
        {savedEntry?.hasKey && (
          <Button
            variant="tertiary"
            onClick={() => {
              updateProviderField(provider.id, "apiKey", "");
              setReplacingKeys((current) => ({ ...current, [provider.id]: false }));
            }}
          >
            Cancel
          </Button>
        )}
      </Flex>
    );
  };

  const renderProviderRow = (provider) => {
    const savedEntry = saved?.providers?.[provider.id];
    const entry = form[provider.id];

    return (
      <Box key={provider.id} padding={4} hasRadius background="neutral100">
        <Flex justifyContent="space-between" alignItems="center">
          <Typography fontWeight="bold">{provider.label}</Typography>
          {savedEntry?.hasKey ? (
            <Flex gap={2} alignItems="center">
              <Typography variant="pi" textColor="success600">
                ✓ Key saved {savedEntry.keyHint}
              </Typography>
              <Button
                variant="secondary"
                size="S"
                onClick={() => handleTest(provider.id)}
                loading={testResults[provider.id]?.status === "running"}
              >
                Test
              </Button>
              <Button variant="danger-light" size="S" onClick={() => handleClearKey(provider.id)}>
                Remove key
              </Button>
            </Flex>
          ) : (
            <Typography variant="pi" textColor="neutral500">
              No key saved
            </Typography>
          )}
        </Flex>
        {testResults[provider.id]?.text && (
          <Box paddingTop={1}>
            <Typography
              variant="pi"
              textColor={testResults[provider.id].status === "ok" ? "success600" : "danger600"}
            >
              {testResults[provider.id].status === "ok" ? "✓ " : "✕ "}
              {testResults[provider.id].text}
            </Typography>
          </Box>
        )}
        <Flex gap={2} paddingTop={2} alignItems="flex-end" wrap="wrap">
          <Box style={{ flex: 2, minWidth: 260 }}>
            <Typography variant="pi" fontWeight="bold" textColor="neutral600">
              API key
            </Typography>
            {renderKeyInput(provider, savedEntry, entry)}
          </Box>
          <Box style={{ flex: 1, minWidth: 200 }}>
            <Typography variant="pi" fontWeight="bold" textColor="neutral600">
              Model ID (optional)
            </Typography>
            <TextInput
              name={`ai-model-${provider.id}`}
              value={entry?.model ?? ""}
              onChange={(event) => updateProviderField(provider.id, "model", event.target.value)}
              placeholder={`Default: ${provider.modelPlaceholder}`}
            />
            <Typography variant="pi" textColor="neutral500">
              Exact model ID like "{provider.modelPlaceholder}" — leave empty to use the default
            </Typography>
          </Box>
        </Flex>
      </Box>
    );
  };

  return (
    <Box background="neutral0" hasRadius shadow="filterShadow" padding={6}>
      <Flex justifyContent="space-between" alignItems="center" paddingBottom={4}>
        <Box>
          <Typography variant="delta" tag="h2">
            AI settings
          </Typography>
          <Typography variant="pi" textColor="neutral500">
            API keys are encrypted (AES-256-GCM) before being stored in the database
          </Typography>
        </Box>
        <Flex gap={2}>
          <Button variant="tertiary" onClick={onClose}>
            Back to presets
          </Button>
          <Button onClick={handleSave} loading={isSaving}>
            Save AI settings
          </Button>
        </Flex>
      </Flex>

      {notice && (
        <Box
          padding={3}
          marginBottom={4}
          hasRadius
          background={notice.type === "danger" ? "danger100" : "success100"}
        >
          <Typography textColor={notice.type === "danger" ? "danger600" : "success600"}>
            {notice.text}
          </Typography>
        </Box>
      )}

      <Box paddingBottom={4} style={{ maxWidth: 320 }}>
        <Typography variant="pi" fontWeight="bold" textColor="neutral600">
          Default provider
        </Typography>
        <SingleSelect
          value={defaultProvider}
          onChange={(value) => setDefaultProvider(value)}
          placeholder="First configured provider"
        >
          {PROVIDERS.map((provider) => (
            <SingleSelectOption key={provider.id} value={provider.id}>
              {provider.label}
            </SingleSelectOption>
          ))}
        </SingleSelect>
      </Box>

      <Flex direction="column" alignItems="stretch" gap={3}>
        {PROVIDERS.map(renderProviderRow)}
      </Flex>

      <Box paddingTop={4}>
        <Typography variant="pi" textColor="neutral500">
          Environment variables (CKSTUDIO_AI_*_KEY) still work as a fallback when no key is saved
          here
        </Typography>
      </Box>
    </Box>
  );
};

AISettingsPanel.propTypes = {
  onClose: PropTypes.func.isRequired,
};

export default AISettingsPanel;
