import React, { useState } from 'react';
import { 
  useIsProposeChangesModalOpen,
  useProposeChangesRequest,
  useUISelector,
} from '../../contexts/UIContext';

const prettyJson = (obj: any) => {
  try { return JSON.stringify(obj, null, 2); } catch { return String(obj); }
};

const ProposeChangesModal = function ProposeChangesModal() {
  const open = useIsProposeChangesModalOpen();
  // const setOpen = useSetIsProposeChangesModalOpen();
  const req = useProposeChangesRequest();
  const resolve = useUISelector((s) => s.resolveProposeChanges);
  const [userReason, setUserReason] = useState('');

  const goal = (req && (req.arguments?.goal ?? req.goal)) || '';
  const actions = (req && (req.arguments?.actions ?? req.actions)) || [];
  const checks = (req && (req.arguments?.checks ?? req.checks)) || [];

  if (!open) return null;


  // Decision is communicated via a custom event the ChatContext listens to (by ref),
  // or via a resolver in UIContext that is handled when the modal closes. Here we
  // emit a DOM event; ChatContext doesn't need to import this component directly.
  const resolveDecision = (approved: boolean) => {
    resolve({ approved, user_reason: approved ? undefined : (userReason || undefined) });
  };

  return (
    <div className="fixed inset-0 flex items-center justify-center p-4 z-50">
      <div className="absolute inset-0 bg-black/40 backdrop-blur-sm" onClick={() => resolveDecision(false)} />
      <div className="bg-background-light dark:bg-background-dark border border-gray-200 dark:border-gray-700 rounded-2xl shadow-xl w-full max-w-3xl relative z-10 overflow-hidden">
        <div className="flex justify-between items-center p-6 border-b border-gray-200 dark:border-gray-700">
          <h2 className="text-xl font-semibold text-text-light dark:text-text-dark">Review proposed changes</h2>
        </div>
        <div className="p-6 space-y-5 max-h-[70vh] overflow-y-auto">
          {goal && (
            <div>
              <div className="text-sm font-semibold mb-1">Goal</div>
              <div className="text-sm text-gray-800 dark:text-gray-200 whitespace-pre-wrap">{goal}</div>
            </div>
          )}
          {Array.isArray(actions) && actions.length > 0 && (
            <div>
              <div className="text-sm font-semibold mb-2">Actions ({actions.length})</div>
              <pre className="text-xs bg-gray-100 dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-lg p-3 overflow-auto">
                {prettyJson(actions)}
              </pre>
            </div>
          )}
          {Array.isArray(checks) && checks.length > 0 && (
            <div>
              <div className="text-sm font-semibold mb-2">Post-apply checks</div>
              <pre className="text-xs bg-gray-100 dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-lg p-3 overflow-auto">
                {prettyJson(checks)}
              </pre>
            </div>
          )}
          <div>
            <label className="block text-sm font-medium mb-1">Reason (if rejecting)</label>
            <input
              value={userReason}
              onChange={(e) => setUserReason(e.target.value)}
              placeholder="Optional"
              className="w-full text-sm px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-900 focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
        </div>
        <div className="p-6 border-t border-gray-200 dark:border-gray-700 flex justify-end gap-3">
          <button onClick={() => resolveDecision(false)} className="text-sm text-black dark:text-white rounded-3xl px-4 py-1.5 border border-gray-300 bg-gray-200/35 hover:bg-gray-200/75 dark:bg-background-dark dark:border-gray-600 dark:hover:bg-gray-300/10">Cancel</button>
          <button onClick={() => resolveDecision(false)} className="text-sm rounded-3xl px-4 py-1.5 border border-gray-300 bg-gray-200/50 hover:bg-gray-200/75 dark:bg-background-dark dark:border-gray-600 dark:hover:bg-gray-300/10">Reject</button>
          <button onClick={() => resolveDecision(true)} className="bg-green-600 hover:bg-green-700 text-white text-sm px-4 py-1.5 rounded-3xl">Approve</button>
        </div>
      </div>
    </div>
  );
}

export default React.memo(ProposeChangesModal);
