import React, { useState, useEffect } from 'react';
import { Search, Filter, Download, Save, CheckCircle, AlertCircle, FileText, ExternalLink, MessageSquare, ChevronDown, ChevronRight, Eye, EyeOff, Upload, HelpCircle } from 'lucide-react';
import { formatDdMmYyyy } from '@/lib/vnDateFormat';

const SecurityQuestionnaire = () => {
  // Parse the JSON data from the uploaded file
  const jsonData = {
    "ID": {
      "0": "4.1a", "1": "4.2a", "2": "4.3a", "3": "4.4a", "4": "5.1a", "5": "5.2a", "6": "5.3a", "7": "6.1a", 
      "8": "6.1b", "9": "6.1c", "10": "6.2a", "11": "6.3a", "12": "7.1a", "13": "7.2a", "14": "7.3a", 
      "15": "7.4a", "16": "7.5a", "17": "7.5b", "18": "8.1a", "19": "8.2a", "20": "8.3a", "21": "9.1a", 
      "22": "9.2a", "23": "9.2b", "24": "9.3a", "25": "9.3b", "26": "10.1a", "27": "10.2a"
    },
    "Question": {
      "0": "Has the organization determined external and internal issues that are relevant to and affect the ISMS' ability to achieve its intended outcomes?",
      "1": "Has the organization identified interested parties relevant to the ISMS, their relevant requirements and which of these will be addressed by the ISMS?",
      "2": "Has the organization determined the scope of its ISMS?",
      "3": "Has the organization established, implemented, maintained, and continually improves an ISMS in accordance with the requirements of ISO/IEC 27001:2022?",
      "4": "Are the objectives of the ISMS compatible with the organization's strategic direction and mission?",
      "5": "Is an Information Security Policy available and appropriate to the purpose and context of the organization and does it support the strategic direction of the company?",
      "6": "Has the organization's top management established (and are they supportive of,) a mechanism for communicating responsibilities and authorities for roles relevant to information security within the organization?",
      "7": "Has organization defined and applied an information security risk assessment process?",
      "8": "Does the organization have a documented risk treatment process?",
      "9": "Has the organization produced a Statement of Applicability (SoA)?",
      "10": "Has the organization established information security objectives at applicable functions and levels within the business and are they consistent with the Information Security Policy?",
      "11": "When the organization determines the need for changes to the information security management system, are the changes carried out in a planned manner?",
      "12": "Has the organization determined and does it provide the resources needed for the establishment, implementation, maintenance, and continual improvement of the ISMS?",
      "13": "Has the organization determined the necessary competence of person(s) doing work under its control that affects its information security performance?",
      "14": "Are the organizations employees made aware of the Information Security Policy?",
      "15": "Has the organization determined the need for internal and external communications relevant to the ISMS?",
      "16": "Does the organization's ISMS include documented information as required by ISO/IEC 27001:2022?",
      "17": "Is documented information required by the ISMS and ISO/IEC 27001:2022 controlled?",
      "18": "Has the organization planned, implemented and does it control the processes needed to meet requirements, and to implement the actions determined in Clause 6 (Planning)?",
      "19": "Does the organization perform information security risk assessments at planned intervals or when significant changes are proposed or occur?",
      "20": "Has the organization implemented an information security risk treatment plan?",
      "21": "Has the organization determined what needs to monitored and measured, including information security processes and controls?",
      "22": "Does the organization conduct internal audits of their ISMS at planned intervals?",
      "23": "Has the organization planned, established, implemented and does it maintain an audit programme(s), including the frequency, methods, responsibilities, planning requirements and reporting?",
      "24": "Does the organizations top management review the organization's ISMS at planned intervals to ensure its continuing suitability, adequacy and effectiveness?",
      "25": "Do the results of management reviews include decisions related to continual improvement opportunities and any needs for changes to the ISMS?",
      "26": "Does the organization continually improve the suitability, adequacy, and effectiveness of their ISMS?",
      "27": "When a nonconformity occurs, does the organization react to the nonconformity, and as applicable take action to control and correct it?"
    }
  };

  const [responses, setResponses] = useState({});
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [expandedSections, setExpandedSections] = useState(new Set(['4', '5', '6', '7', '8', '9', '10']));
  const [showCompleted, setShowCompleted] = useState(true);
  const [showPending, setShowPending] = useState(true);
  const [validationErrors, setValidationErrors] = useState(new Set());
  const [showHelpModal, setShowHelpModal] = useState(false);
  const [autoSaveStatus, setAutoSaveStatus] = useState('saved');

  // Parse data into structured format
  const questions = Object.keys(jsonData.ID).map(key => ({
    index: key,
    id: jsonData.ID[key],
    question: jsonData.Question[key],
    response: responses[key]?.response || '',
    policy: responses[key]?.policy || '',
    document: responses[key]?.document || '',
    reference: responses[key]?.reference || '',
    comments: responses[key]?.comments || ''
  }));

  // Group questions by main clause (4, 5, 6, 7, 8, 9, 10)
  const groupedQuestions = questions.reduce((acc, question) => {
    const category = question.id.split('.')[0];
    if (!acc[category]) {
      acc[category] = [];
    }
    acc[category].push(question);
    return acc;
  }, {});

  const categoryNames = {
    '4': 'Context of the Organization (4.x)',
    '5': 'Leadership (5.x)',
    '6': 'Planning (6.x)', 
    '7': 'Support (7.x)',
    '8': 'Operation (8.x)',
    '9': 'Performance Evaluation (9.x)',
    '10': 'Improvement (10.x)'
  };

  // Filter questions based on search and category
  const filteredQuestions = questions.filter(question => {
    const matchesSearch = question.question.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         question.id.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesCategory = selectedCategory === 'all' || question.id.startsWith(selectedCategory);
    const matchesCompletion = (showCompleted && question.response) || (showPending && !question.response);
    return matchesSearch && matchesCategory && matchesCompletion;
  });

  const handleResponseChange = (index, field, value) => {
    setResponses(prev => ({
      ...prev,
      [index]: {
        ...prev[index],
        [field]: value
      }
    }));

    setAutoSaveStatus('saving');
    
    // Auto-save functionality
    setTimeout(() => {
      setAutoSaveStatus('saved');
    }, 1000);
  };

  const toggleSection = (category) => {
    const newExpanded = new Set(expandedSections);
    if (newExpanded.has(category)) {
      newExpanded.delete(category);
    } else {
      newExpanded.add(category);
    }
    setExpandedSections(newExpanded);
  };

  const exportData = () => {
    const exportData = questions.map(q => ({
      ID: q.id,
      Question: q.question,
      'Select your response from the dropdown box.': responses[q.index]?.response || '',
      'Enter the details of the Policy related to this requirement (if applicable)': responses[q.index]?.policy || '',
      'Enter the details of the any other document related to this requirement (if applicable)': responses[q.index]?.document || '',
      'Enter the document(s) reference details or a link to the document': responses[q.index]?.reference || '',
      'Add comments or enter a customised response here.': responses[q.index]?.comments || ''
    }));
    
    const dataStr = JSON.stringify(exportData, null, 2);
    const dataBlob = new Blob([dataStr], {type: 'application/json'});
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'iso27001_2022_responses.json';
    link.click();
  };

  const importData = (event) => {
    const file = event.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const data = JSON.parse(e.target.result);
          const newResponses = {};
          data.forEach((item, index) => {
            newResponses[index.toString()] = {
              response: item['Select your response from the dropdown box.'] || '',
              policy: item['Enter the details of the Policy related to this requirement (if applicable)'] || '',
              document: item['Enter the details of the any other document related to this requirement (if applicable)'] || '',
              reference: item['Enter the document(s) reference details or a link to the document'] || '',
              comments: item['Add comments or enter a customised response here.'] || ''
            };
          });
          setResponses(newResponses);
          setAutoSaveStatus('imported');
          setTimeout(() => setAutoSaveStatus('saved'), 2000);
        } catch (error) {
          alert('Error importing file. Please check the format.');
        }
      };
      reader.readAsText(file);
    }
  };

  const getCompletionStats = () => {
    const total = questions.length;
    const completed = questions.filter(q => responses[q.index]?.response).length;
    return { completed, total, percentage: Math.round((completed / total) * 100) };
  };

  const stats = getCompletionStats();

  const responseOptions = [
    { value: 'yes', label: 'Yes - Fully Implemented', color: 'text-green-700 bg-green-50' },
    { value: 'partial', label: 'Partially Implemented', color: 'text-yellow-700 bg-yellow-50' },
    { value: 'no', label: 'No - Not Implemented', color: 'text-red-700 bg-red-50' },
    { value: 'na', label: 'Not Applicable', color: 'text-gray-700 bg-gray-50' },
    { value: 'planned', label: 'Planned for Implementation', color: 'text-blue-700 bg-blue-50' }
  ];

  const HelpModal = () => (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" onClick={() => setShowHelpModal(false)}>
      <div className="bg-white rounded-lg p-6 max-w-2xl mx-4 max-h-96 overflow-y-auto" onClick={e => e.stopPropagation()}>
        <div className="flex justify-between items-center mb-4">
          <h3 className="text-lg font-semibold">ISO 27001:2022 Questionnaire Help</h3>
          <button onClick={() => setShowHelpModal(false)} className="text-gray-400 hover:text-gray-600">
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        <div className="space-y-4 text-sm">
          <div>
            <h4 className="font-medium text-gray-900">Response Options:</h4>
            <ul className="mt-2 space-y-1 text-gray-600">
              <li><strong>Yes - Fully Implemented:</strong> The control is completely in place and functioning</li>
              <li><strong>Partially Implemented:</strong> The control is partially in place but needs improvement</li>
              <li><strong>No - Not Implemented:</strong> The control is not in place</li>
              <li><strong>Not Applicable:</strong> The control doesn't apply to your organization</li>
              <li><strong>Planned for Implementation:</strong> The control is planned but not yet implemented</li>
            </ul>
          </div>
          <div>
            <h4 className="font-medium text-gray-900">Navigation Tips:</h4>
            <ul className="mt-2 space-y-1 text-gray-600">
              <li>Use the search bar to find specific questions</li>
              <li>Filter by category to focus on specific clauses</li>
              <li>Toggle sections using the chevron icons</li>
              <li>Progress is automatically saved as you work</li>
            </ul>
          </div>
          <div>
            <h4 className="font-medium text-gray-900">Documentation:</h4>
            <p className="mt-2 text-gray-600">
              Fill in policy details, document references, and comments to provide evidence and context for your responses.
              This documentation will be valuable during audits.
            </p>
          </div>
        </div>
      </div>
    </div>
  );

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header Toolbar */}
      <div className="sticky top-0 z-40 bg-white border-b border-gray-200 shadow-sm">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-16">
            <div className="flex items-center space-x-4">
              <h1 className="text-xl font-semibold text-gray-900">ISO 27001:2022 ISMS Questionnaire</h1>
              <div className="flex items-center space-x-2 text-sm text-gray-600">
                <CheckCircle className="h-4 w-4 text-green-500" />
                <span>{stats.completed}/{stats.total} completed ({stats.percentage}%)</span>
              </div>
            </div>
            
            <div className="flex items-center space-x-3">
              <button
                onClick={() => setShowHelpModal(true)}
                className="inline-flex items-center px-3 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50"
                title="Help and guidance"
              >
                <HelpCircle className="h-4 w-4 mr-2" />
                Help
              </button>
              
              <label className="inline-flex items-center px-3 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 cursor-pointer">
                <Upload className="h-4 w-4 mr-2" />
                Import
                <input
                  type="file"
                  accept=".json"
                  onChange={importData}
                  className="hidden"
                />
              </label>
              
              <button
                onClick={exportData}
                className="inline-flex items-center px-3 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50"
              >
                <Download className="h-4 w-4 mr-2" />
                Export
              </button>
              
              <button className="inline-flex items-center px-3 py-2 border border-transparent rounded-md text-sm font-medium text-white bg-blue-600 hover:bg-blue-700">
                <Save className="h-4 w-4 mr-2" />
                Save Progress
              </button>
            </div>
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        <div className="flex flex-col lg:flex-row gap-6">
          
          {/* Sidebar */}
          <div className="lg:w-80 space-y-6">
            {/* Search and Filters */}
            <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
              <div className="space-y-4">
                {/* Search Bar */}
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
                  <input
                    type="text"
                    placeholder="Search questions..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>

                {/* Category Filter */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">ISO Clause</label>
                  <select
                    value={selectedCategory}
                    onChange={(e) => setSelectedCategory(e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"
                  >
                    <option value="all">All Clauses</option>
                    <option value="4">4 - Context of Organization</option>
                    <option value="5">5 - Leadership</option>
                    <option value="6">6 - Planning</option>
                    <option value="7">7 - Support</option>
                    <option value="8">8 - Operation</option>
                    <option value="9">9 - Performance Evaluation</option>
                    <option value="10">10 - Improvement</option>
                  </select>
                </div>

                {/* Completion Filter */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Show</label>
                  <div className="space-y-2">
                    <label className="flex items-center">
                      <input
                        type="checkbox"
                        checked={showCompleted}
                        onChange={(e) => setShowCompleted(e.target.checked)}
                        className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                      />
                      <span className="ml-2 text-sm text-gray-700">Completed ({stats.completed})</span>
                    </label>
                    <label className="flex items-center">
                      <input
                        type="checkbox"
                        checked={showPending}
                        onChange={(e) => setShowPending(e.target.checked)}
                        className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                      />
                      <span className="ml-2 text-sm text-gray-700">Pending ({stats.total - stats.completed})</span>
                    </label>
                  </div>
                </div>
              </div>
            </div>

            {/* Progress Overview */}
            <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
              <h3 className="text-sm font-medium text-gray-900 mb-3">Progress by Clause</h3>
              <div className="space-y-3">
                {Object.entries(categoryNames).map(([category, name]) => {
                  const categoryQuestions = groupedQuestions[category] || [];
                  const completed = categoryQuestions.filter(q => responses[q.index]?.response).length;
                  const total = categoryQuestions.length;
                  const percentage = total > 0 ? Math.round((completed / total) * 100) : 0;
                  
                  return (
                    <div key={category}>
                      <div className="flex justify-between text-xs text-gray-600 mb-1">
                        <span>{name}</span>
                        <span>{completed}/{total}</span>
                      </div>
                      <div className="w-full bg-gray-200 rounded-full h-2">
                        <div 
                          className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                          style={{ width: `${percentage}%` }}
                        />
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>

          {/* Main Content */}
          <div className="flex-1">
            <div className="bg-white rounded-lg shadow-sm border border-gray-200">
              {/* Questions by Category */}
              {Object.entries(categoryNames).map(([category, categoryName]) => {
                const categoryQuestions = (groupedQuestions[category] || []).filter(question => {
                  const matchesSearch = question.question.toLowerCase().includes(searchTerm.toLowerCase()) ||
                                       question.id.toLowerCase().includes(searchTerm.toLowerCase());
                  const matchesCompletion = (showCompleted && responses[question.index]?.response) || (showPending && !responses[question.index]?.response);
                  return matchesSearch && (selectedCategory === 'all' || selectedCategory === category) && matchesCompletion;
                });

                if (categoryQuestions.length === 0) return null;

                const isExpanded = expandedSections.has(category);

                return (
                  <div key={category} className="border-b border-gray-200 last:border-b-0">
                    <button
                      onClick={() => toggleSection(category)}
                      className="w-full px-6 py-4 text-left hover:bg-gray-50 focus:outline-none focus:bg-gray-50 transition-colors"
                    >
                      <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-3">
                          {isExpanded ? (
                            <ChevronDown className="h-5 w-5 text-gray-400" />
                          ) : (
                            <ChevronRight className="h-5 w-5 text-gray-400" />
                          )}
                          <h2 className="text-lg font-semibold text-gray-900">{categoryName}</h2>
                        </div>
                        <span className="text-sm text-gray-500">
                          {categoryQuestions.filter(q => responses[q.index]?.response).length}/{categoryQuestions.length} completed
                        </span>
                      </div>
                    </button>

                    {isExpanded && (
                      <div className="px-6 pb-4">
                        <div className="space-y-6">
                          {categoryQuestions.map((question) => (
                            <div key={question.index} className="border border-gray-200 rounded-lg p-6 bg-gray-50">
                              <div className="space-y-4">
                                {/* Question Header */}
                                <div className="flex items-start justify-between">
                                  <div className="flex-1">
                                    <div className="flex items-center space-x-3 mb-2">
                                      <span className="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-blue-100 text-blue-800">
                                        {question.id}
                                      </span>
                                      {responses[question.index]?.response && (
                                        <CheckCircle className="h-4 w-4 text-green-500" />
                                      )}
                                    </div>
                                    <p className="text-gray-900 font-medium leading-relaxed">{question.question}</p>
                                  </div>
                                </div>

                                {/* Response Selection */}
                                <div className="space-y-3">
                                  <label className="block text-sm font-medium text-gray-700">Response *</label>
                                  <select
                                    value={responses[question.index]?.response || ''}
                                    onChange={(e) => handleResponseChange(question.index, 'response', e.target.value)}
                                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"
                                  >
                                    <option value="">Select your response from the dropdown box...</option>
                                    {responseOptions.map((option) => (
                                      <option key={option.value} value={option.value}>
                                        {option.label}
                                      </option>
                                    ))}
                                  </select>
                                </div>

                                {/* Additional Fields */}
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                  <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-2">
                                      <FileText className="inline h-4 w-4 mr-1" />
                                      Policy Details
                                    </label>
                                    <textarea
                                      value={responses[question.index]?.policy || ''}
                                      onChange={(e) => handleResponseChange(question.index, 'policy', e.target.value)}
                                      placeholder="Enter the details of the Policy related to this requirement (if applicable)"
                                      rows={3}
                                      className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"
                                    />
                                  </div>
                                  
                                  <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-2">
                                      <FileText className="inline h-4 w-4 mr-1" />
                                      Other Documents
                                    </label>
                                    <textarea
                                      value={responses[question.index]?.document || ''}
                                      onChange={(e) => handleResponseChange(question.index, 'document', e.target.value)}
                                      placeholder="Enter the details of any other document related to this requirement (if applicable)"
                                      rows={3}
                                      className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"
                                    />
                                  </div>
                                </div>

                                <div>
                                  <label className="block text-sm font-medium text-gray-700 mb-2">
                                    <ExternalLink className="inline h-4 w-4 mr-1" />
                                    Document References/Links
                                  </label>
                                  <input
                                    type="text"
                                    value={responses[question.index]?.reference || ''}
                                    onChange={(e) => handleResponseChange(question.index, 'reference', e.target.value)}
                                    placeholder="Enter the document(s) reference details or a link to the document"
                                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"
                                  />
                                </div>

                                <div>
                                  <label className="block text-sm font-medium text-gray-700 mb-2">
                                    <MessageSquare className="inline h-4 w-4 mr-1" />
                                    Comments
                                  </label>
                                  <textarea
                                    value={responses[question.index]?.comments || ''}
                                    onChange={(e) => handleResponseChange(question.index, 'comments', e.target.value)}
                                    placeholder="Add comments or enter a customised response here."
                                    rows={3}
                                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"
                                  />
                                </div>

                                {/* Status Indicator */}
                                {responses[question.index]?.response && (
                                  <div className="flex items-center space-x-2">
                                    <div className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${
                                      responseOptions.find(opt => opt.value === responses[question.index].response)?.color || 'bg-gray-100 text-gray-800'
                                    }`}>
                                      {responseOptions.find(opt => opt.value === responses[question.index].response)?.label || responses[question.index].response}
                                    </div>
                                    <span className="text-xs text-gray-500">Last updated: {formatDdMmYyyy(new Date())}</span>
                                  </div>
                                )}
                              </div>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                );
              })}

              {/* Empty State */}
              {filteredQuestions.length === 0 && (
                <div className="px-6 py-12 text-center">
                  <AlertCircle className="mx-auto h-12 w-12 text-gray-400 mb-4" />
                  <h3 className="text-lg font-medium text-gray-900 mb-2">No questions found</h3>
                  <p className="text-gray-500 mb-4">Try adjusting your search terms or filters.</p>
                  <button
                    onClick={() => {
                      setSearchTerm('');
                      setSelectedCategory('all');
                      setShowCompleted(true);
                      setShowPending(true);
                    }}
                    className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-blue-700 bg-blue-100 hover:bg-blue-200 transition-colors"
                  >
                    Clear All Filters
                  </button>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Status Bar */}
      <div className="sticky bottom-0 bg-white border-t border-gray-200 shadow-lg">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-14">
            <div className="flex items-center space-x-6">
              <div className="flex items-center space-x-2">
                <CheckCircle className="h-5 w-5 text-green-500" />
                <span className="text-sm text-gray-700">
                  {stats.completed} of {stats.total} requirements completed
                </span>
              </div>
              
              <div className="flex items-center space-x-2">
                {validationErrors.size > 0 ? (
                  <>
                    <AlertCircle className="h-5 w-5 text-red-500" />
                    <span className="text-sm text-red-700">
                      {validationErrors.size} validation errors
                    </span>
                  </>
                ) : (
                  <>
                    <CheckCircle className="h-5 w-5 text-green-500" />
                    <span className="text-sm text-green-700">All responses valid</span>
                  </>
                )}
              </div>
            </div>

            <div className="flex items-center space-x-3">
              <div className="flex items-center space-x-2">
                {autoSaveStatus === 'saving' && (
                  <div className="flex items-center space-x-2">
                    <div className="animate-spin rounded-full h-3 w-3 border-b-2 border-blue-600"></div>
                    <span className="text-xs text-gray-500">Saving...</span>
                  </div>
                )}
                {autoSaveStatus === 'saved' && (
                  <span className="text-xs text-green-600">Auto-saved</span>
                )}
                {autoSaveStatus === 'imported' && (
                  <span className="text-xs text-blue-600">Data imported successfully</span>
                )}
              </div>
              
              <div className="flex items-center space-x-2">
                <button 
                  className="p-2 text-gray-400 hover:text-gray-600 transition-colors"
                  title="Undo last change"
                >
                  <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6" />
                  </svg>
                </button>
                <button 
                  className="p-2 text-gray-400 hover:text-gray-600 transition-colors"
                  title="Redo last change"
                >
                  <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 10h-10a8 8 0 00-8 8v2m18-10l-6 6m6-6l-6-6" />
                  </svg>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Help Modal */}
      {showHelpModal && <HelpModal />}
    </div>
  );
};

export default SecurityQuestionnaire;