import React, { useEffect } from "react";
import { wpFetch } from "../utils/wpApi";
import { useNotice } from "../context/NoticeContext";


export default function ApiConfigurationCard() {
  const { showNotice } = useNotice();
  const [sheetId, setSheetId] = React.useState("");
  const [secretKey, setSecretKey] = React.useState("");
  const [copyText, setCopyText] = React.useState("Copy");

  const fetchConfig = async () => {
    const response = await wpFetch( 'get-config' );
    if ( response.success && response.data ) {
      const data = response.data;
      setSheetId( data.sheet_id );
      setSecretKey( data.secret_key );
      return;
    } else {
      showNotice("Failed to load configuration", "error");
    }
  }

  const saveConfig = async () => {
    const response = await wpFetch( 'save-config', {
      method: 'POST',
      data: {
        sheet_id: sheetId,
        secret_key: secretKey,
      },
    } );
    if ( response.success ) {
      showNotice("Configuration saved successfully", "success");
    } else {
      showNotice("Failed to save configuration", "error");
    }
  }

  const generateKey = () => {
    let newKey = "";
    while (newKey.length < 32) {
      newKey += Math.random().toString(36).substring(2, 15);
    }
    setSecretKey(newKey.substring(0, 32));
    showNotice("New secret key generated, save changes to apply", "success");
  }

  const copyKey = () => {
    navigator.clipboard.writeText(secretKey);
    setCopyText("Copied!");
    setTimeout(() => setCopyText("Copy"), 2000);
  }

  useEffect(() => {
    fetchConfig();
  }, []);

  return (
    <div className="wpgsa-card">
      <div className="wpgsa-card-header">
        <h2>API Configuration</h2>
        <p>Configure your Google Sheets API settings below.</p>
      </div>

      <div className="wpgsa-card-body">
        <div className="wpgsa-field">
          <label>Google Sheet ID</label>
          <input
            type="text"
            value={sheetId}
            onChange={(e) => setSheetId(e.target.value)}
          />
          <small>Found in the sheet URL (between /d/ and /edit)</small>
        </div>

        <div className="wpgsa-field">
          <label>Secret Key</label>
          <div className="wpgsa-inline">
            <input
              type="text"
              value={secretKey}
              onChange={(e) => setSecretKey(e.target.value)}
            readOnly
          />
          <button className="wpgsa-btn wpgsa-btn-secondary" style={{ width: "100px" }} onClick={copyKey}>{copyText}</button>
          <button className="wpgsa-btn wpgsa-btn-secondary" onClick={generateKey}>
            Generate New Key
          </button>
        </div>
        <small>
            Used for secure API authentication between the sheet and your store.
          </small>
        </div>

        <button className="wpgsa-btn wpgsa-btn-primary" onClick={saveConfig}>
          Save Changes
        </button>
      </div>
    </div>
  );
}
