import React, { useState, useMemo } from 'react';
import {
  useIsReadApprovalModalOpen,
  useReadApprovalRequest,
  useUISelector,
} from '../../contexts/UIContext';
import { ASSISTANT_BRAND_NAME } from '../../constants';

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

const ReadApprovalModal: React.FC = () => {
  const open = useIsReadApprovalModalOpen();
  const payload = useReadApprovalRequest();
  const resolve = useUISelector((s) => s.resolveReadApproval);
  const [declineReason, setDeclineReason] = useState('');

  const requestArgs = useMemo(() => {
    const req = payload?.request ?? payload;
    if (!req) return {};
    if (req.arguments && typeof req.arguments === 'object') {
      return req.arguments;
    }
    return {};
  }, [payload]);

  const resource = (requestArgs?.resource as string | undefined) || 'unknown';
  const responsePreview = payload?.response;

  if (!open) return null;

  const handleResolve = (approved: boolean) => {
    resolve({
      approved,
      user_reason: approved ? undefined : (declineReason?.trim() || undefined),
    });
    setDeclineReason('');
  };

  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={() => handleResolve(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">
            Share site data?
          </h2>
        </div>
        <div className="p-6 space-y-5 max-h-[70vh] overflow-y-auto">
          <p className="text-sm text-gray-700 dark:text-gray-200 leading-relaxed">
            {`${ASSISTANT_BRAND_NAME} is requesting to read data from your site. Review the request and preview below. Approving will share this data with the assistant for the current turn only.`}
          </p>

          <div>
            <div className="text-sm font-semibold mb-1">Requested resource</div>
            <div className="text-sm text-gray-800 dark:text-gray-200">
              {resource}
            </div>
          </div>

          {Object.keys(requestArgs).length > 0 && (
            <div>
              <div className="text-sm font-semibold mb-2">Request details</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(requestArgs)}
              </pre>
            </div>
          )}

          <div>
            <div className="text-sm font-semibold mb-2">Data preview</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(responsePreview ?? { message: 'No data available for preview.' })}
            </pre>
          </div>

          <div>
            <label className="block text-sm font-medium mb-1">Reason (optional, if declining)</label>
            <input
              value={declineReason}
              onChange={(e) => setDeclineReason(e.target.value)}
              placeholder="Add a note for your records"
              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={() => handleResolve(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={() => handleResolve(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"
          >
            Decline
          </button>
          <button
            onClick={() => handleResolve(true)}
            className="bg-blue-600 hover:bg-blue-700 text-white text-sm px-4 py-1.5 rounded-3xl"
          >
            Approve & Share
          </button>
        </div>
      </div>
    </div>
  );
};

export default React.memo(ReadApprovalModal);
