'use client';

import { useState, useEffect } from 'react';
import { useRouter, usePathname, useSearchParams } from 'next/navigation';

import SiteSelector from '@/components/dashboards/SiteSelector';
import SiteStatus from '@/components/dashboards/SiteStatus';
import EnergyLineChart from '@/components/dashboards/EnergyLineChart';
import KPI_Table from '@/components/dashboards/KPIStatus';
import MonthlyBarChart from '@/components/dashboards/MonthlyBarChart';
import DashboardLayout from './dashlayout';

import { SiteName, SiteDetails, mockSiteData } from '@/types/SiteData';

const AdminDashboard = () => {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const siteParam = searchParams?.get('site');
  const validSiteNames: SiteName[] = ['Site A', 'Site B', 'Site C'];

  const [selectedSite, setSelectedSite] = useState<SiteName>(() => {
    if (siteParam && validSiteNames.includes(siteParam as SiteName)) {
      return siteParam as SiteName;
    }
    return 'Site A';
  });

  // Keep siteParam and selectedSite in sync
  useEffect(() => {
    if (
      siteParam &&
      validSiteNames.includes(siteParam as SiteName) &&
      siteParam !== selectedSite
    ) {
      setSelectedSite(siteParam as SiteName);
    }
  }, [siteParam, selectedSite]);

  // Update query string when site is changed manually
  const handleSiteChange = (newSite: SiteName) => {
    setSelectedSite(newSite);
    const newUrl = `${pathname}?site=${encodeURIComponent(newSite)}`;
    router.push(newUrl);
  };

  const currentSiteDetails: SiteDetails = mockSiteData[selectedSite] || {
    location: 'N/A',
    inverterProvider: 'N/A',
    emergencyContact: 'N/A',
    lastSyncTimestamp: 'N/A',
    consumptionData: [],
    generationData: [],
    systemStatus: 'N/A',
    temperature: 'N/A',
    solarPower: 0,
    realTimePower: 0,
    installedPower: 0,
  };

  const handleCSVExport = () => {
    alert('Exported raw data to CSV (mock)');
  };

  const handlePDFExport = () => {
    alert('Exported chart images to PDF (mock)');
  };

  return (
    <DashboardLayout>
      <div className="px-6 space-y-6">
        <h1 className="text-lg font-semibold">Admin Dashboard</h1>

        <div className="grid md:grid-cols-2 gap-6">
          <div className="space-y-4">
            <SiteSelector
              selectedSite={selectedSite}
              setSelectedSite={handleSiteChange}
            />
            <SiteStatus
              selectedSite={selectedSite}
              location={currentSiteDetails.location}
              inverterProvider={currentSiteDetails.inverterProvider}
              emergencyContact={currentSiteDetails.emergencyContact}
              lastSyncTimestamp={currentSiteDetails.lastSyncTimestamp}
            />
          </div>

          <div>
            <KPI_Table siteData={currentSiteDetails} />
          </div>
        </div>

        <div className="grid md:grid-cols-2 gap-6">
          <div className="pb-5">
            <EnergyLineChart
              consumptionData={currentSiteDetails.consumptionData}
              generationData={currentSiteDetails.generationData}
            />
          </div>
          <div className="pb-5">
            <MonthlyBarChart siteData={currentSiteDetails} />
          </div>
        </div>

        <div className="flex flex-col md:flex-row gap-4 justify-center">
          <button onClick={handleCSVExport} className="text-sm lg:text-lg btn-primary">
            Export Raw Data to CSV
          </button>
          <button onClick={handlePDFExport} className="text-sm lg:text-lg btn-primary">
            Export Chart Images to PDF
          </button>
        </div>
      </div>
    </DashboardLayout>
  );
};

export default AdminDashboard;


