import { useState, useCallback } from 'react';
import { useNavigate } from '@remix-run/react';
import type { Mandate } from '~/types/mandate';
import { createScopedLogger } from '~/utils/logger';
import { classNames } from '~/utils/classNames';

const logger = createScopedLogger('MandateSubmission');

interface MandateSubmissionProps {
  initialMandate?: Mandate;
}

/**
 * MandateSubmission component for submitting structured mandates to bolt.diy.
 * This replaces the free-form chat interface with a structured mandate API.
 */
export function MandateSubmission({ initialMandate }: MandateSubmissionProps) {
  const [mandate, setMandate] = useState<Mandate | null>(initialMandate || null);
  const [status, setStatus] = useState<'idle' | 'submitting' | 'accepted' | 'error'>('idle');
  const [error, setError] = useState<string | null>(null);
  const [eventStreamUrl, setEventStreamUrl] = useState<string | null>(null);
  const navigate = useNavigate();

  const handleSubmit = useCallback(async () => {
    if (!mandate) {
      setError('No mandate to submit');
      return;
    }

    setStatus('submitting');
    setError(null);

    try {
      const response = await fetch('/api/mandate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(mandate),
      });

      if (response.status === 202) {
        const result = await response.json() as { event_stream_url?: string; mandate_id?: string };
        setStatus('accepted');
        setEventStreamUrl(result.event_stream_url || null);
        
        // Navigate to observability dashboard
        if (result.mandate_id) {
          navigate(`/observability/${result.mandate_id}`);
        }
      } else {
        const errorData = await response.json() as { error?: string };
        setError(errorData.error || `HTTP ${response.status}: ${response.statusText}`);
        setStatus('error');
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Unknown error';
      logger.error(`Failed to submit mandate: ${errorMessage}`);
      setError(errorMessage);
      setStatus('error');
    }
  }, [mandate, navigate]);

  return (
    <div className="flex flex-col h-full w-full bg-bolt-elements-background-depth-1 p-8">
      <div className="max-w-4xl mx-auto w-full">
        <div className="mb-6">
          <h1 className="text-2xl font-bold text-bolt-elements-textPrimary mb-2">
            Mandate Submission
          </h1>
          <p className="text-sm text-bolt-elements-textSecondary">
            Submit a structured mandate for autonomous code execution. Mandates are typically generated by CorporateSwarm governance system.
          </p>
        </div>

        {status === 'accepted' && eventStreamUrl && (
          <div className="mb-4 p-4 bg-green-500/10 border border-green-500/20 rounded-lg">
            <p className="text-sm text-green-500">
              Mandate accepted! Execution started. Redirecting to observability dashboard...
            </p>
          </div>
        )}

        {error && (
          <div className="mb-4 p-4 bg-red-500/10 border border-red-500/20 rounded-lg">
            <p className="text-sm text-red-500">Error: {error}</p>
          </div>
        )}

        <div className="bg-bolt-elements-background-depth-2 border border-bolt-elements-borderColor rounded-lg p-6">
          {mandate ? (
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-bolt-elements-textPrimary mb-2">
                  Mandate ID
                </label>
                <div className="text-sm text-bolt-elements-textSecondary font-mono bg-bolt-elements-background-depth-3 p-2 rounded">
                  {mandate.mandate_id}
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-bolt-elements-textPrimary mb-2">
                  Objectives
                </label>
                <ul className="list-disc list-inside text-sm text-bolt-elements-textSecondary space-y-1">
                  {mandate.objectives.map((obj, idx) => (
                    <li key={idx}>{obj}</li>
                  ))}
                </ul>
              </div>

              <div>
                <label className="block text-sm font-medium text-bolt-elements-textPrimary mb-2">
                  Budget
                </label>
                <div className="text-sm text-bolt-elements-textSecondary space-y-1">
                  <div>Tokens: {mandate.budget.token.toLocaleString()}</div>
                  <div>Time: {mandate.budget.time}s</div>
                  <div>Cost: ${mandate.budget.cost.toFixed(2)}</div>
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-bolt-elements-textPrimary mb-2">
                  Constraints
                </label>
                <div className="text-sm text-bolt-elements-textSecondary space-y-1">
                  <div>Language: {mandate.constraints.language}</div>
                  <div>Max Dependencies: {mandate.constraints.maxDependencies}</div>
                  <div>No Network: {mandate.constraints.noNetwork ? 'Yes' : 'No'}</div>
                  <div>Max Files: {mandate.constraints.maxFiles}</div>
                </div>
              </div>

              <div className="pt-4 border-t border-bolt-elements-borderColor">
                <button
                  onClick={handleSubmit}
                  disabled={status === 'submitting' || status === 'accepted'}
                  className={classNames(
                    'px-4 py-2 rounded-md text-sm font-medium',
                    'bg-accent-500 text-white',
                    'hover:bg-accent-600',
                    'disabled:opacity-50 disabled:cursor-not-allowed',
                    'transition-colors'
                  )}
                >
                  {status === 'submitting' ? 'Submitting...' : status === 'accepted' ? 'Accepted' : 'Submit Mandate'}
                </button>
              </div>
            </div>
          ) : (
            <div className="text-center py-12">
              <p className="text-bolt-elements-textSecondary mb-4">
                No mandate available. Mandates are typically provided by the CorporateSwarm governance system.
              </p>
              <p className="text-sm text-bolt-elements-textTertiary">
                To view execution status, navigate to the observability dashboard.
              </p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

