import { useState, useEffect } from 'react';
import { DiffEditor } from '@monaco-editor/react';
import { projectsAPI } from '../api';
import { useTheme } from '../context/ThemeContext';
import './TemplateUpdateModal.css';

function TemplateUpdateModal({ projectId, resource, onClose, onComplete }) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [templateDiff, setTemplateDiff] = useState(null);
  const [loadingDiff, setLoadingDiff] = useState(true);
  const { theme } = useTheme();

  const loadTemplateDiff = async () => {
    setLoadingDiff(true);
    try {
      const response = await projectsAPI.getTemplateDiff(
        projectId,
        resource.uid,
        resource.rawYaml
      );
      setTemplateDiff(response.data);
    } catch (err) {
      setError(err.response?.data?.detail || 'Failed to generate template diff');
    } finally {
      setLoadingDiff(false);
    }
  };

  // Load template diff when component mounts
  useEffect(() => {
    loadTemplateDiff();
  }, []);

  const handleUpdateTemplate = async () => {
    setLoading(true);
    setError('');

    try {
      await projectsAPI.updateTemplate(
        projectId,
        resource.uid,
        resource.rawYaml
      );
      onComplete();
    } catch (err) {
      setError(err.response?.data?.detail || 'Failed to update template');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal template-update-modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-header">
          <h3>Update Template File</h3>
          <button className="close-btn" onClick={onClose}>×</button>
        </div>

        <div className="modal-body">
          <div className="template-info-box">
            <h4>📝 Template Changes Detected</h4>
            <p>
              You modified the rendered resource <strong>{resource.kind}/{resource.name}</strong>.
              This will update the corresponding template file.
            </p>
          </div>

          {loadingDiff ? (
            <div className="loading-section">
              <div className="loading"></div>
              <p>Generating template diff...</p>
            </div>
          ) : error ? (
            <div className="error-box">
              <strong>Error:</strong>
              <p>{error}</p>
            </div>
          ) : templateDiff ? (
            <>
              <div className="template-details">
                <div className="detail-item">
                  <span className="detail-label">Template File:</span>
                  <code>{templateDiff.template_file}</code>
                </div>
                <div className="detail-item">
                  <span className="detail-label">Changes:</span>
                  <span className="change-badge">
                    {templateDiff.additions} additions, {templateDiff.deletions} deletions
                  </span>
                </div>
              </div>

              <div className="diff-section">
                <div className="diff-header">
                  <strong>Template File Diff (Original ← → Modified):</strong>
                </div>
                <DiffEditor
                  height="500px"
                  language="yaml"
                  original={templateDiff.original_template}
                  modified={templateDiff.modified_template}
                  theme={theme === 'dark' ? 'vs-dark' : 'vs-light'}
                  options={{
                    readOnly: true,
                    automaticLayout: true,
                    renderSideBySide: true,
                    scrollBeyondLastLine: false,
                    minimap: { enabled: true },
                  }}
                />
              </div>

              <div className="warning-box">
                <strong>⚠️ Important:</strong>
                <ul>
                  <li>This will modify the template file in your chart</li>
                  <li>Changes may affect other resources if the template uses conditions</li>
                  <li>Make sure to review the diff carefully before confirming</li>
                  <li>You can re-render after updating to see the effect</li>
                </ul>
              </div>
            </>
          ) : null}
        </div>

        <div className="modal-footer">
          <button className="btn btn-outline" onClick={onClose} disabled={loading}>
            Cancel
          </button>
          <button 
            className="btn btn-primary" 
            onClick={handleUpdateTemplate}
            disabled={loading || loadingDiff || !!error}
          >
            {loading ? (
              <>
                <div className="loading"></div>
                Updating...
              </>
            ) : (
              '✓ Update Template'
            )}
          </button>
        </div>
      </div>
    </div>
  );
}

export default TemplateUpdateModal;
