import { comparisonCandidateData } from '@/helper/candidate.helper';
import { getComparisonSchema, getDemographicsData } from '@/lib/db/comparision';
import { Candidate } from '@/type/candidate.type';
import { useState } from 'react';
import { AssetMixChart } from './components/AssetMixChart';
import { CaseTypeChart } from './components/CaseTypeChart';
import { ComparisonTable } from './components/ComparisonTable';
import { DemographicsSection } from './components/DemographicsSection';
import { ExpenseChart } from './components/ExpenseChart';
import { FamilyWealthChart } from './components/FamilyWealthChart';
import { LiabilitiesChart } from './components/LiabilitiesChart';
import { ProjectsChart } from './components/ProjectsChart';

const ComparisonAnalytics = ({
  showAnalytics,
  selectedData,
  selectedCandidates,
}: {
  showAnalytics: boolean;
  selectedData: Candidate[];
  selectedCandidates: number[];
}) => {
  const comparisonSchema = getComparisonSchema();
  const demographicsData = getDemographicsData();

  const [collapsedGroups, setCollapsedGroups] = useState<Set<string>>(new Set());

  // Toggle group collapse
  const toggleGroup = (groupId: string) => {
    setCollapsedGroups((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(groupId)) {
        newSet.delete(groupId);
      } else {
        newSet.add(groupId);
      }
      return newSet;
    });
  };

  return (
    <section
      id="analytics-view"
      className={`mt-4 pt-4 md:mt-16 md:pt-16 pb-32 md:pb-12 border-t border-blue-100 animate-fade-in ${!showAnalytics ? 'hidden' : ''}`}
    >
      <div className="flex items-center justify-between mb-1.5 pt-0">
        <h3 className="text-base md:text-xl font-bold text-blue-900 border-l-4 border-yellow-500 pl-2">
          নির্বাচিত প্রার্থীদের বিস্তারিত তুলনা
        </h3>
      </div>

      <ComparisonTable
        selectedData={comparisonCandidateData(selectedData)}
        selectedCandidates={selectedCandidates}
        comparisonSchema={comparisonSchema}
        collapsedGroups={collapsedGroups}
        toggleGroup={toggleGroup}
      />

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-2 md:gap-3">
        <FamilyWealthChart selectedData={selectedData} />
        <ExpenseChart selectedData={selectedData} />
        <AssetMixChart selectedData={selectedData} />

        <CaseTypeChart selectedData={selectedData} />
        <ProjectsChart selectedData={selectedData} />
        <LiabilitiesChart selectedData={selectedData} />
      </div>

      <DemographicsSection demographicsData={demographicsData} />
    </section>
  );
};

export default ComparisonAnalytics;
