import React, { useState } from 'react';
import { useSetIsLoginModalOpen } from '../contexts/UIContext';
import { ASSISTANT_BRAND_NAME, getRestNonce, PLUGIN_REST_ENDPOINTS } from '../constants';

type SetupState = {
  assistantEnabled: boolean;
  allowLogReads: boolean;
  allowWriteOperations: boolean;
  requireReadApproval: boolean;
};

const ToggleRow: React.FC<{
  label: string;
  description: string;
  checked: boolean;
  disabled?: boolean;
  onChange: (checked: boolean) => void;
}> = ({ label, description, checked, disabled = false, onChange }) => {
  return (
    <label
      className={`flex items-start gap-4 rounded-xl border border-gray-200 dark:border-gray-700 p-4 ${
        disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'
      }`}
    >
      <span className="relative inline-flex w-11 h-6 flex-shrink-0">
        <input
          type="checkbox"
          checked={checked}
          disabled={disabled}
          onChange={(e) => onChange(e.target.checked)}
          className="peer sr-only"
        />
        <span className="absolute inset-0 rounded-full border border-gray-300 dark:border-gray-600 bg-gray-200 dark:bg-gray-800 transition peer-checked:bg-blue-600 peer-checked:border-blue-600" />
        <span className="absolute left-[2px] top-[2px] h-5 w-5 rounded-full bg-white shadow transition peer-checked:translate-x-5" />
      </span>
      <span className="space-y-1">
        <span className="block text-sm font-semibold text-gray-900 dark:text-gray-100">{label}</span>
        <span className="block text-sm text-gray-600 dark:text-gray-300">{description}</span>
      </span>
    </label>
  );
};

const InitialSetupGate: React.FC = () => {
  const setIsLoginModalOpen = useSetIsLoginModalOpen();
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [setup, setSetup] = useState<SetupState>({
    // Always start setup with strict defaults. Fresh installs should opt in explicitly.
    assistantEnabled: false,
    allowLogReads: false,
    allowWriteOperations: false,
    requireReadApproval: false,
  });

  const updateSetup = (patch: Partial<SetupState>) => {
    setSetup((prev) => ({ ...prev, ...patch }));
  };

  const handleAssistantToggle = (enabled: boolean) => {
    if (!enabled) {
      updateSetup({
        assistantEnabled: false,
        allowLogReads: false,
        allowWriteOperations: false,
        requireReadApproval: false,
      });
      return;
    }

    updateSetup({ assistantEnabled: true });
  };

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

    try {
      const response = await fetch(PLUGIN_REST_ENDPOINTS.settings, {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': getRestNonce() },
        body: JSON.stringify({
          assistantEnabled: setup.assistantEnabled,
          allowLogReads: setup.allowLogReads,
          allowWriteOperations: setup.allowWriteOperations,
          requireReadApproval: setup.requireReadApproval,
          setupCompleted: true,
        }),
      });

      if (!response.ok) {
        let message = 'Failed to save setup.';
        let nextSettings: Partial<SetupState> | null = null;
        try {
          const payload = await response.json();
          if (payload?.message && typeof payload.message === 'string') {
            message = payload.message;
          }
          if (payload?.settings && typeof payload.settings === 'object') {
            nextSettings = {
              assistantEnabled: Boolean(payload.settings.assistantEnabled),
              allowLogReads: Boolean(payload.settings.allowLogReads),
              allowWriteOperations: Boolean(payload.settings.allowWriteOperations),
              requireReadApproval: Boolean(payload.settings.requireReadApproval),
            };
          }
          if (nextSettings) {
            setSetup((prev) => ({ ...prev, ...nextSettings }));
          }
        } catch {
          // Ignore parse errors and use fallback.
        }
        throw new Error(message);
      }

      window.location.reload();
    } catch (e) {
      const message = e instanceof Error ? e.message : 'Failed to save setup.';
      setError(message);
      setIsSaving(false);
    }
  };

  return (
    <div className="flex flex-1 items-center justify-center px-4 sm:px-6 py-6 sm:py-8">
      <div className="w-full max-w-3xl rounded-2xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-background-dark shadow-xl p-6 sm:p-8 space-y-6">
        <div className="space-y-3">
          <h1 className="text-2xl sm:text-3xl font-semibold text-text-light dark:text-text-dark">
            {`Welcome to ${ASSISTANT_BRAND_NAME}`}
          </h1>
          <p className="text-sm sm:text-base text-gray-700 dark:text-gray-300">
            Choose your default safety settings before getting started. You can change these anytime in
            Plugin Settings.
          </p>
        </div>

        <div className="space-y-3">
          <ToggleRow
            label={`Enable ${ASSISTANT_BRAND_NAME}`}
            description="Sends your prompts & necessary site data to our AI service."
            checked={setup.assistantEnabled}
            onChange={handleAssistantToggle}
          />
          <ToggleRow
            label="Allow Log Reads (72h)"
            description={`Reads sanitized excerpts from the WordPress debug log for 72 hours. This works only when WP_DEBUG_LOG is set to an absolute file path. ${ASSISTANT_BRAND_NAME} never creates or writes the log file.`}
            checked={setup.allowLogReads}
            disabled={!setup.assistantEnabled}
            onChange={(checked) => updateSetup({ allowLogReads: checked })}
          />
          <ToggleRow
            label="Allow Write Operations"
            description={`Allows ${ASSISTANT_BRAND_NAME} to propose changes to your site. Nothing is applied without your explicit approval.`}
            checked={setup.allowWriteOperations}
            disabled={!setup.assistantEnabled}
            onChange={(checked) => updateSetup({ allowWriteOperations: checked })}
          />
          <ToggleRow
            label="Per-Request Approval for Reads"
            description="Show a preview and ask me every time before sharing site data."
            checked={setup.requireReadApproval}
            disabled={!setup.assistantEnabled}
            onChange={(checked) => updateSetup({ requireReadApproval: checked })}
          />
        </div>

        <div className="rounded-xl border border-amber-200 dark:border-amber-900/60 bg-amber-50 dark:bg-amber-900/20 p-4">
          <p className="text-sm font-semibold text-amber-900 dark:text-amber-200 mb-1">
            With great power comes great responsibility.
          </p>
          <p className="text-sm text-amber-800 dark:text-amber-300">
            {`${ASSISTANT_BRAND_NAME} is meant to be a helpful tool, but it can and does make mistakes. AI generated`}
            {' '}
            outputs should not be taken as fact, and AI generated changes should be carefully reviewed
            before they are published to a live site. Please use this tool with caution.
          </p>
        </div>

        {error && (
          <div className="rounded-lg border border-red-200 dark:border-red-900/60 bg-red-50 dark:bg-red-900/20 p-3 text-sm text-red-700 dark:text-red-300">
            {error}
          </div>
        )}

        <div className="flex flex-col sm:flex-row gap-3 sm:items-center sm:justify-between">
          <button
            type="button"
            onClick={() => setIsLoginModalOpen(true)}
            className="text-sm text-left sm:text-center px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-background-light dark:bg-background-dark hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
          >
            Create free account
          </button>
          <div className="flex flex-col sm:flex-row gap-3">
            <button
              type="button"
              onClick={handleSave}
              disabled={isSaving}
              className={`px-4 py-2 text-sm rounded-lg text-white bg-blue-600 hover:bg-blue-700 transition-colors ${
                isSaving ? 'opacity-60 cursor-not-allowed' : ''
              }`}
            >
              {isSaving ? 'Saving...' : 'Save Setup'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default InitialSetupGate;
