import React, { useState, useEffect } from 'react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, PieChart, Pie, Cell, LineChart, Line } from 'recharts';
import { CheckCircle, AlertTriangle, XCircle, FileText, Shield, Users, Settings, TrendingUp, Download, Upload, Eye, Clock, AlertCircle } from 'lucide-react';
import SecurityQuestionnaire from '../checklists/iso27001-questionnaire';
import ISO27001ClauseQuestionnaire from '../checklists/iso27001-questionnaire-ui';
import { useNavigate } from 'react-router-dom';
import Navigation from './CCFNavigation';
import CCFNavigation from './CCFNavigation';


// Type definitions
export interface Alert {
  id: string;
  severity: string;
  type: string;
  message: string;
  date: string;
  vendor: string;
  identity: string;
}

export interface Question {
  id: string;
  clause: string;
  category: string;
  question: string;
  response: 'Yes' | 'No' | 'Not Applicable' | 'Partially' | '';
  evidence: string;
  comments: string;
  clarificationRequired: boolean;
  riskLevel: 'Low' | 'Medium' | 'High' | 'Critical';
}

export interface ClauseData {
  id: string;
  title: string;
  questions: Record<string, string[]>;
  completionRate: number;
  complianceScore: number;
  riskScore: number;
}

export interface ControlAssessment {
  id: string;
  name: string;
  status: number;
  implemented: boolean;
  riskLevel: 'Low' | 'Medium' | 'High' | 'Critical';
  lastReviewed: string;
  nextReview: string;
  controls?: number;
}

export type ISOQuestions = Record<string, string[]>;

// Utility functions
export const getStatusColor = (score: number) => {
  if (score >= 85) return 'text-green-600';
  if (score >= 70) return 'text-yellow-600';
  if (score >= 50) return 'text-orange-600';
  return 'text-red-600';
};

export const getStatusIcon = (score: number) => {
  if (score >= 85) return <CheckCircle className="w-5 h-5 text-green-600" />;
  if (score >= 70) return <AlertTriangle className="w-5 h-5 text-yellow-600" />;
  if (score >= 50) return <AlertCircle className="w-5 h-5 text-orange-600" />;
  return <XCircle className="w-5 h-5 text-red-600" />;
};

export const getRiskBadgeClass = (riskLevel: string) => {
  switch (riskLevel) {
    case 'Low': return 'bg-green-100 text-green-800 border border-green-200';
    case 'Medium': return 'bg-yellow-100 text-yellow-800 border border-yellow-200';
    case 'High': return 'bg-orange-100 text-orange-800 border border-orange-200';
    case 'Critical': return 'bg-red-100 text-red-800 border border-red-200';
    default: return 'bg-gray-100 text-gray-800 border border-gray-200';
  }
};


export const tabs = [
    { id: 'gaps', label: 'Clause Checklist', icon: FileText },
    { id: 'reports', label: 'Annex Checklist', icon: FileText },
    { id: 'overview', label: 'Executive Overview', icon: TrendingUp }
];

const CCFDashboard: React.FC = () => {
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState< string| "overview"| "iso27001"| "controls" |'gaps' | 'reports' >('controls');
  const [clauseData, setClauseData] = useState<ClauseData[]>([]);

  

  // Initialize sample data based on ISO 27001:2022 structure for banking
  useEffect(() => {
    const initializeData = () => {
      const clauses: ClauseData[] = [
        {
          id: '4',
          title: 'Context of the Organization',
          questions: {"4.1_Understanding the organization and its context": [
        "Have you documented the external and internal issues relevant to your organization\u2019s purpose and information security objectives?",
        "How do you identify and review external issues (e.g., political, economic, technological trends)?",
        "How are internal issues (e.g., organizational structure, resources, capabilities) assessed?",
        "Who is responsible for monitoring changes in these external and internal issues?",
        "How often is the context reviewed or updated?",
        "Can you show evidence of how these issues have influenced your ISMS?"
    ],
    "4.2_Understanding the needs and expectations of interested parties": [
        "Have you identified the interested parties that are relevant to the ISMS?",
        "What method is used to determine the needs and expectations of those interested parties?",
        "Are legal, regulatory, and contractual requirements included in the identified needs?",
        "How do you ensure the identified needs are up to date?",
        "Which of these requirements are addressed through the ISMS?",
        "Can you show how these needs and expectations are documented and monitored?"
    ],
    "4.3_Determining the scope of the information security management system": [
        "How is the scope of your ISMS defined?",
        "Is the scope based on external and internal issues, as well as interested party requirements?",
        "Are interfaces and dependencies with external parties considered when determining scope?",
        "Is the defined scope aligned with the organization's activities, services, and products?",
        "Is the ISMS scope documented and available to stakeholders?",
        "How often is the scope reviewed or updated?"
    ],
    "4.4_Information security management system": [
        "Has your organization established an ISMS in accordance with ISO/IEC 27001?",
        "What processes and controls are part of your ISMS?",
        "How are these processes interacting or integrated with other business processes?",
        "What are the procedures for maintaining and improving the ISMS?",
        "Who is responsible for maintaining the ISMS?",
        "Can you show evidence of continual improvement (e.g., updates, internal audits, corrective actions)?",
        "How is effectiveness of the ISMS measured?"
    ]},
          completionRate: 92,
          complianceScore: 88,
          riskScore: 15
        },
        {
          id: '5',
          title: 'Leadership & Governance',
          questions: {"5.1_Leadership_and_commitment": [
        "Has top management established an information security policy and objectives aligned with the organization’s strategic direction?",
        "Are the ISMS requirements integrated into the organization’s business processes?",
        "Has top management ensured that adequate resources are available for the ISMS?",
        "Is the importance of effective information security and compliance communicated clearly by top management?",
        "Does top management ensure that the ISMS achieves its intended outcomes?",
        "Are individuals encouraged and supported to contribute to the effectiveness of the ISMS?",
        "Is continual improvement of the ISMS promoted by top management?",
        "Do all relevant managers demonstrate leadership in their areas of responsibility?"
    ],
    "5.2_Policy": [
        "Has top management established an information security policy appropriate to the organization's purpose?",
        "Does the policy include a framework for setting measurable information security objectives?",
        "Does the policy include commitments to satisfy applicable requirements and to continually improve the ISMS?",
        "Is the policy documented, communicated within the organization, and available to interested parties as appropriate?"
    ],
    "5.3_Organizational_roles_responsibilities_and_authorities": [
        "Are roles and responsibilities for information security clearly assigned and communicated?",
        "Has top management assigned responsibility for ensuring ISMS compliance with ISO 27001?",
        "Is there a designated role responsible for reporting ISMS performance to top management?"
    ]},
          completionRate: 95,
          complianceScore: 90,
          riskScore: 12
        },
        {
          id: '6',
          title: 'Planning & Risk Management',
          questions: {"6.1.1_Actions_to_address_risks_and_opportunities": [
        "Has the organization considered internal/external issues and stakeholder requirements when planning the ISMS?",
        "Have risks and opportunities to the ISMS’s objectives been identified and addressed?",
        "Are there plans to integrate these actions into the ISMS and evaluate their effectiveness?"
    ],
    "6.1.2_Information_security_risk_assessment": [
        "Is there a defined and documented risk assessment process in place?",
        "Does the process include criteria for risk acceptance and assessment?",
        "Are risk assessments repeatable and consistent in outcome?",
        "Are all relevant risks to confidentiality, integrity, and availability identified and owners assigned?",
        "Are consequences and likelihoods assessed and risk levels determined?",
        "Are risks evaluated against risk criteria and prioritized for treatment?",
        "Is documented information retained for the risk assessment process?"
    ],
    "6.1.3_Information_security_risk_treatment": [
        "Is there a defined and documented risk treatment process?",
        "Are treatment options selected based on the risk assessment results?",
        "Are required controls identified and compared with Annex A to ensure none are missed?",
        "Is a Statement of Applicability (SoA) prepared with justifications for included/excluded controls?",
        "Is there a risk treatment plan, and is it approved by the risk owners?",
        "Is documented information retained for the risk treatment process?"
    ],
    "6.2_Information_security_objectives": [
        "Are information security objectives established at relevant levels and functions?",
        "Are objectives measurable, consistent with the policy, and based on risk treatment results?",
        "Are objectives monitored, communicated, and updated as appropriate?",
        "Is there a documented plan that defines what will be done, resources required, responsibilities, deadlines, and how results are evaluated?"
    ],
    "6.3_Planning_of_changes": [
        "Are changes to the ISMS planned and controlled in a systematic way?"
    ]},
          completionRate: 88,
          complianceScore: 82,
          riskScore: 25
        },
        {
          id: '7',
          title: 'Support & Resources',
          questions: {"7.1_Resources": [
        "Have the necessary resources for establishing, implementing, maintaining, and improving the ISMS been identified?",
        "Are sufficient resources allocated to support the ISMS activities?"
    ],
    "7.2_Competence": [
        "How does the organization determine the necessary competence for roles affecting information security?",
        "What evidence exists to show personnel meet competence requirements?",
        "What actions are taken if personnel lack required competencies?",
        "Is the effectiveness of competence-related actions evaluated?",
        "Is documented information on competence retained?"
    ],
    "7.3_Awareness": [
        "How are personnel made aware of the information security policy?",
        "Are employees aware of their role in improving information security performance?",
        "Do employees understand the implications of not conforming to ISMS requirements?"
    ],
    "7.4_Communication": [
        "What internal and external ISMS communications are needed?",
        "Who is responsible for communicating, and when?",
        "What methods are used to communicate ISMS-related information?",
        "Are communication responsibilities clearly documented?"
    ],
    "7.5_Documented Information": [
        "Does the ISMS include required documented information?",
        "Has the organization determined what additional documented information is necessary?",
        "How is documented information created and updated (e.g., format, identification, approval)?",
        "How is access to and protection of documented information ensured?",
        "Are controls in place for distribution, retrieval, and use of documents?",
        "Are version control, retention, and disposal practices implemented?",
        "How is externally-sourced documented information identified and controlled?"
    ]},
          completionRate: 91,
          complianceScore: 85,
          riskScore: 18
        },
        {
          id: '8',
          title: 'Operational Security',
          questions: {"8.1_Operational Planning and Control": [
        "Are processes planned, implemented, and controlled to meet ISMS requirements?",
        "Have criteria for process control been established and implemented?",
        "Is documented information available to confirm planned processes are executed?",
        "How are planned changes controlled and unintended changes reviewed?",
        "Are externally provided services or processes relevant to the ISMS controlled?"
    ],
    "8.2_Information Security Risk Assessment": [
        "Are information security risk assessments conducted at planned intervals and when significant changes occur?",
        "Are the criteria established in clause 6.1.2 a) applied?",
        "Is documented information of risk assessment results retained?"
    ],
    "8.3_Information Security Risk Treatment": [
        "Has the risk treatment plan been implemented?",
        "Is there documented evidence of the results of the risk treatment process?"
    ]},
          completionRate: 85,
          complianceScore: 78,
          riskScore: 32
        },
        {
          id: '9',
          title: 'Performance Evaluation',
          questions: {"9.1_Monitoring, measurement, analysis and evaluation": [
        "What information security processes and controls are being monitored and measured?",
        "What methods are used for monitoring, measurement, analysis, and evaluation?",
        "How do you ensure that the monitoring and measurement methods produce valid and reproducible results?",
        "When are the monitoring and measurement activities performed?",
        "Who is responsible for monitoring and measuring information security performance?",
        "When are the results analyzed and evaluated?",
        "Who is responsible for analyzing and evaluating the results?",
        "Can you provide documented evidence of monitoring and measurement results?",
        "How is information security performance evaluated?",
        "How is the effectiveness of the ISMS evaluated?"
    ],
    "9.2_Internal audit": [
        "Are internal audits conducted at planned intervals?",
        "Do internal audits assess conformity with organizational and ISO/IEC 27001 requirements?",
        "Do audits evaluate the effective implementation and maintenance of the ISMS?",
        "Is there an internal audit programme established and maintained?",
        "How is the frequency of audits determined?",
        "Are audit responsibilities, methods, and reporting clearly defined?",
        "How are the importance of processes and results of previous audits considered in planning?",
        "Are audit criteria and scope defined for each audit?",
        "How is auditor objectivity and impartiality ensured?",
        "Are audit results reported to relevant management?",
        "Is documented evidence of audit programmes and results maintained?"
    ],
    "9.3_Management review": [
        "Is top management reviewing the ISMS at planned intervals?",
        "Are actions from previous management reviews tracked and reviewed?",
        "Are changes in external and internal issues considered during management reviews?",
        "Are changes in needs and expectations of interested parties reviewed?",
        "Is feedback on information security performance reviewed (e.g., trends in nonconformities, measurement, audits, objectives)?",
        "Is feedback from interested parties considered?",
        "Are the results of risk assessments and status of risk treatment plans reviewed?",
        "Are opportunities for continual improvement discussed?",
        "Do management review results include decisions on improvements and necessary ISMS changes?"
    ]},
          completionRate: 83,
          complianceScore: 75,
          riskScore: 28
        },
        {
          id: '10',
          title: 'Continuous Improvement',
          questions: {"10.1_Continual_improvement": [
      "Has the organization established a process to continually improve the suitability, adequacy, and effectiveness of the ISMS?",
      "Can you provide examples of continual improvement initiatives taken for the ISMS over the past year?",
      "Are results from monitoring, audits, and reviews used as inputs to improvement actions?"
    ],
    "10.2_Nonconformity_and_corrective_action": [
      "Is there a documented process for handling nonconformities within the ISMS?",
      "When a nonconformity occurs, does the organization take action to control and correct it?",
      "Does the organization deal with the consequences of nonconformities appropriately?",
      "Does the organization review the nonconformity, determine its causes, and identify if similar nonconformities exist or could occur?",
      "Are corrective actions implemented and their effectiveness reviewed?",
      "Are updates made to the ISMS if necessary following corrective actions?",
      "Is documented information retained as evidence of the nature of nonconformities, actions taken, and the results of corrective actions?"
    ]},
          complianceScore: 80,
          completionRate: 87,
          riskScore: 22
        }
      ];

      setClauseData(clauses);
    };

    initializeData();
  }, []);

  const overallComplianceScore = clauseData.length > 0 
    ? Math.round(clauseData.reduce((sum, clause) => sum + clause.complianceScore, 0) / clauseData.length)
    : 0;

  const overallRiskScore = clauseData.length > 0
    ? Math.round(clauseData.reduce((sum, clause) => sum + clause.riskScore, 0) / clauseData.length)
    : 0;

  const overallCompletionRate = clauseData.length > 0
    ? Math.round(clauseData.reduce((sum, clause) => sum + clause.completionRate, 0) / clauseData.length)
    : 0;

  const handleAlert = (alert: ClauseData) => {
    navigate(`/profytRadar/iso27001/${alert.id}`, { state: { alert } });
  };

  return (
    <div className="w-full min-h-screen bg-background">
      
      <CCFNavigation setActiveTab={setActiveTab} />

      <main className="flex w-full mx-auto py-4">
        {activeTab === 'controls'}

        {activeTab === 'gaps' && <ISO27001ClauseQuestionnaire/>}

        {activeTab === 'reports' && <SecurityQuestionnaire />}
      </main>
    </div>
  );
};





export default CCFDashboard;