import { useState, useRef } from "react";
import SectionCard from "./SectionCard";
import Toggle from "./Toggle";
import SaveToast from "./SaveToast";
import { getAjaxUrl, getNonce } from "../../utils/api";
import { getAdminConfig } from "../../utils/helpers";

const EXPORT_ACTION = "ai_image_export_settings";
const IMPORT_ACTION = "ai_image_import_settings";

function TipBox({ children, variant = "info" }) {
  const styles =
    variant === "warning"
      ? "bg-amber-50/80 border-amber-100 text-amber-950"
      : "bg-gray-50 border-gray-100 text-gray-600";

  return (
    <div className={`p-3.5 rounded-md border ${styles}`}>
      <div className="flex gap-2">
        <svg
          className={`w-4 h-4 flex-shrink-0 mt-0.5 ${variant === "warning" ? "text-amber-600" : "text-gray-400"}`}
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
          strokeWidth={2}
        >
          {variant === "warning" ? (
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M12 9v2m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
            />
          ) : (
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
            />
          )}
        </svg>
        <div className="flex-1 text-xs leading-relaxed">{children}</div>
      </div>
    </div>
  );
}

export default function ExportImportSection() {
  const config = getAdminConfig();
  const version = config.version || "1.0.0";
  const fileInputRef = useRef(null);

  const [includeApiKeysExport, setIncludeApiKeysExport] = useState(true);
  const [importApiKeys, setImportApiKeys] = useState(true);
  const [selectedFile, setSelectedFile] = useState(null);
  const [exporting, setExporting] = useState(false);
  const [importing, setImporting] = useState(false);
  const [message, setMessage] = useState({ type: null, text: "" });

  const handleExport = async () => {
    setMessage({ type: null, text: "" });
    setExporting(true);
    try {
      const formData = new FormData();
      formData.append("action", EXPORT_ACTION);
      formData.append("nonce", getNonce());
      formData.append("include_api_keys", includeApiKeysExport ? "1" : "0");

      const res = await fetch(getAjaxUrl(), { method: "POST", body: formData });
      const data = await res.json();

      if (!data.success || !data.data?.bundle) {
        throw new Error(data.data?.message || "Export failed.");
      }

      const json = JSON.stringify(data.data.bundle, null, 2);
      const blob = new Blob([json], { type: "application/json" });
      const url = URL.createObjectURL(blob);
      const stamp = new Date().toISOString().slice(0, 10);
      const link = document.createElement("a");
      link.href = url;
      link.download = `ai-image-settings-v${version}-${stamp}.json`;
      document.body.appendChild(link);
      link.click();
      link.remove();
      URL.revokeObjectURL(url);

      setMessage({ type: "success", text: "Settings exported. Your download should start shortly." });
    } catch (err) {
      setMessage({ type: "error", text: err?.message || "Export failed." });
    } finally {
      setExporting(false);
    }
  };

  const handleFileChange = (e) => {
    const file = e.target.files?.[0];
    setSelectedFile(file || null);
    setMessage({ type: null, text: "" });
  };

  const handleImport = async () => {
    if (!selectedFile) {
      setMessage({ type: "error", text: "Please choose a JSON settings file to import." });
      return;
    }

    const confirmed = window.confirm(
      "Importing will overwrite your current plugin settings on this site. Continue?"
    );
    if (!confirmed) return;

    setMessage({ type: null, text: "" });
    setImporting(true);
    try {
      const fileText = await selectedFile.text();
      JSON.parse(fileText);

      const formData = new FormData();
      formData.append("action", IMPORT_ACTION);
      formData.append("nonce", getNonce());
      formData.append("data", fileText);
      formData.append("import_api_keys", importApiKeys ? "1" : "0");

      const res = await fetch(getAjaxUrl(), { method: "POST", body: formData });
      const data = await res.json();

      if (!data.success) {
        throw new Error(data.data?.message || "Import failed.");
      }

      setMessage({ type: "success", text: data.data?.message || "Settings imported." });
      setSelectedFile(null);
      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }

      setTimeout(() => {
        window.location.reload();
      }, 1200);
    } catch (err) {
      const msg =
        err instanceof SyntaxError
          ? "Invalid JSON file. Please select a valid export from this plugin."
          : err?.message || "Import failed.";
      setMessage({ type: "error", text: msg });
    } finally {
      setImporting(false);
    }
  };

  return (
    <SectionCard
      title="Export & Import"
      description="Back up your Instant Image Generator configuration or move settings to another WordPress site."
    >
      <SaveToast message={message} onDismiss={() => setMessage({ type: null, text: "" })} />

      <div className="space-y-6">
          <p className="text-xs font-bold text-gray-500 uppercase tracking-wider mb-4">Export settings</p>

          <div className="rounded-xl border border-gray-200 p-5 space-y-5 bg-white">
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
              <div className="flex-1 min-w-0">
                <p className="text-sm font-semibold text-gray-700">Include API keys</p>
                <p className="mt-1.5 text-xs text-gray-500 leading-relaxed">
                  Turn off when sharing a configuration without secrets. Keys are stored in plain text in the
                  export file.
                </p>
              </div>
              <Toggle
                checked={includeApiKeysExport}
                onChange={setIncludeApiKeysExport}
                id="export-include-api-keys"
              />
            </div>

            <TipBox>
              <p>
                <span className="font-medium text-gray-700">Tip:</span> Export before major changes so you can
                restore your setup quickly.
              </p>
            </TipBox>

            <div className="flex items-center justify-end pt-1 border-t border-gray-100">
              <button
                type="button"
                onClick={handleExport}
                disabled={exporting}
                className="inline-flex items-center gap-2 px-6 py-2.5 bg-gray-800 text-white text-sm font-medium rounded-md hover:bg-gray-900 focus:outline-none focus:ring-2 focus:ring-gray-600 focus:ring-offset-2 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M12 3v12m0 0l-4-4m4 4l4-4M4 21h16" />
                </svg>
                {exporting ? "Exporting…" : "Download Settings File"}
              </button>
            </div>
          </div>
   

        <div className="pt-6 border-t border-gray-100">
          <p className="text-xs font-bold text-gray-500 uppercase tracking-wider mb-4">Import settings</p>

          <div className="rounded-xl border border-gray-200 p-5 space-y-5 bg-white">

            <div>
              <label htmlFor="import-file" className="block text-sm font-semibold text-gray-700 mb-2">
                Settings file
              </label>
              <p className="mt-0 mb-3 text-xs text-gray-500 leading-relaxed">
                Upload a JSON file previously exported from Instant Image Generator.
              </p>
              <input
                ref={fileInputRef}
                id="import-file"
                type="file"
                accept=".json,application/json"
                onChange={handleFileChange}
                disabled={importing}
                className="sr-only"
              />
              <button
                type="button"
                onClick={() => fileInputRef.current?.click()}
                disabled={importing}
                className={`w-full rounded-xl border-2 border-dashed px-6 py-8 text-center transition-all outline-none focus:ring-2 focus:ring-gray-400 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed ${
                  selectedFile
                    ? "border-gray-300 bg-gray-50/80 hover:border-gray-400"
                    : "border-gray-200 bg-gray-50/50 hover:border-gray-300 hover:bg-gray-50"
                }`}
              >
                <span className="inline-flex items-center justify-center w-10 h-10 rounded-full bg-white border border-gray-200 text-gray-500 mb-3">
                  <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
                    />
                  </svg>
                </span>
                {selectedFile ? (
                  <>
                    <p className="text-sm font-semibold text-gray-800">{selectedFile.name}</p>
                    <p className="mt-1 text-xs text-gray-500">Click to choose a different file</p>
                  </>
                ) : (
                  <>
                    <p className="text-sm font-semibold text-gray-700">Choose a .json file</p>
                    <p className="mt-1 text-xs text-gray-500">or click to browse</p>
                  </>
                )}
              </button>
            </div>

            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
              <div className="flex-1 min-w-0">
                <p className="text-sm font-semibold text-gray-700">Import API keys from file</p>
                <p className="mt-1.5 text-xs text-gray-500 leading-relaxed">
                  When off, provider toggles and other settings import but existing API keys on this site are kept.
                </p>
              </div>
              <Toggle checked={importApiKeys} onChange={setImportApiKeys} id="import-api-keys" />
            </div>

            <div className="flex items-center justify-end pt-1 border-t border-gray-100">
              <button
                type="button"
                onClick={handleImport}
                disabled={importing || !selectedFile}
                className="inline-flex items-center gap-2 px-6 py-2.5 bg-gray-800 text-white text-sm font-medium rounded-md hover:bg-gray-900 focus:outline-none focus:ring-2 focus:ring-gray-600 focus:ring-offset-2 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M12 21V9m0 0l4 4m-4-4l-4 4M4 7h16" />
                </svg>
                {importing ? "Importing…" : "Import Settings"}
              </button>
            </div>
          </div>
        </div>
      </div>
    </SectionCard>
  );
}
