'use client';

import { useEffect, useState } from 'react';
import dynamic from 'next/dynamic';
import { Map as MapIcon, Activity } from 'lucide-react';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { ChainageSummaryData } from '@/types';
import { projectSummaryService } from '@/services/api';
import { getDetectionModeConfig } from '@/constants/detectionModeConfig';

// Dynamically import MapModal with SSR disabled (Leaflet requires window object)
const MapModal = dynamic(() => import('@/components/map-modal'), {
  ssr: false,
});

interface DetailedSummarySectionProps {
  projectId: string;
  videoId: string;
  show: boolean;
  detectionType: string;
}

const DetailedSummarySection = ({
  projectId,
  videoId,
  show,
  detectionType,
}: DetailedSummarySectionProps) => {
  const [summaryData, setSummaryData] = useState<ChainageSummaryData | null>(
    null,
  );
  const [loading, setLoading] = useState(false);
  const [showMap, setShowMap] = useState(false);

  useEffect(() => {
    if (!show || !videoId || !projectId) return;

    const fetchSummary = async () => {
      setLoading(true);
      try {
        const data =
          await projectSummaryService.getProjectSummaryByVideo<ChainageSummaryData>(
            projectId,
            videoId,
          );
        setSummaryData(data);
      } catch (err) {
        console.error('Failed to fetch summary:', err);
      } finally {
        setLoading(false);
      }
    };

    fetchSummary();
  }, [show, videoId, projectId]);

  if (!show || loading || !summaryData) return null;

  const modeConfig = getDetectionModeConfig(detectionType);

  // Flatten all detections for the scrollable list
  const allDetections: Array<{
    detection: any;
    chainageName: string;
    packageName: string;
  }> = [];

  Object.entries(summaryData.packages || {}).forEach(
    ([packageName, packageData]) => {
      Object.entries(packageData?.chainages || {}).forEach(
        ([chainageName, chainageData]) => {
          chainageData?.detections?.forEach((detection) => {
            allDetections.push({ detection, chainageName, packageName });
          });
        },
      );
    },
  );

  return (
    <div className="grid grid-cols-1 lg:grid-cols-5 gap-4">
      <Card className="flex flex-col lg:col-span-2 overflow-hidden">
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="p-2 rounded bg-secondary">
                <MapIcon className="h-5 w-5 text-primary" />
              </div>
              <div>
                <CardTitle className="text-base font-bold">Segments</CardTitle>
                <CardDescription className="text-xs">
                  {modeConfig.label} detected
                </CardDescription>
              </div>
            </div>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setShowMap(true)}
              className="gap-2"
            >
              <MapIcon className="h-4 w-4" />
              Map
            </Button>
          </div>
        </CardHeader>
        <CardContent className="flex-1 p-0 overflow-hidden">
          <ScrollArea className="h-[300px] p-4">
            <div className="space-y-4">
              {/* Project Info */}
              <div className="pb-3 border-b">
                <div className="flex flex-col mb-2">
                  <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">
                    Project
                  </span>
                  <span className="text-sm font-bold">
                    {summaryData.project.name}
                  </span>
                </div>
                {summaryData.project.corridor_name && (
                  <div className="flex flex-col">
                    <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">
                      Corridor
                    </span>
                    <span className="text-xs font-semibold text-muted-foreground">
                      {summaryData.project.corridor_name}
                    </span>
                  </div>
                )}
              </div>

              {/* Packages and Chainages */}
              {Object.entries(summaryData.packages).map(
                ([packageName, packageData]) => (
                  <div key={packageData.package_id} className="space-y-2">
                    <div className="text-xs font-bold text-muted-foreground truncate">
                      {packageName}
                    </div>
                    <div className="pl-2 space-y-2 border-l-2 border-muted">
                      {Object.entries(packageData.chainages).map(
                        ([chainageName, chainageData]) => (
                          <div
                            key={chainageData.chainage_id}
                            className="text-xs p-3 rounded-md bg-muted/50 flex items-center justify-between gap-4"
                          >
                            <div className="font-semibold truncate">
                              {chainageName}
                            </div>
                            <div className="text-[10px] bg-background px-2 py-0.5 rounded border font-bold">
                              {chainageData.detection_count}
                            </div>
                          </div>
                        ),
                      )}
                    </div>
                  </div>
                ),
              )}
            </div>
          </ScrollArea>
        </CardContent>
      </Card>

      <Card className="flex flex-col lg:col-span-3 overflow-hidden">
        <CardHeader className="pb-3">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded bg-secondary">
              <Activity className="h-5 w-5 text-primary" />
            </div>
            <div>
              <CardTitle className="text-base font-bold">
                All Detections
              </CardTitle>
              <CardDescription className="text-xs">
                Complete list with GPS coordinates
              </CardDescription>
            </div>
          </div>
        </CardHeader>
        <CardContent className="flex-1 p-0 overflow-hidden">
          <ScrollArea className="h-[300px] p-4">
            <div className="space-y-2">
              {allDetections.map(({ detection, chainageName }, idx) => (
                <div
                  key={`${detection.id}-${idx}`}
                  className="text-xs p-3 bg-muted/30 border rounded-md hover:bg-muted/50 transition-colors"
                >
                  <div className="flex items-center justify-between mb-2">
                    <span className="font-bold">
                      {(detection.class || detection.type || '').replace(
                        /_/g,
                        ' ',
                      )}{' '}
                      #{detection.id}
                    </span>
                    <Badge variant="outline" className="text-[10px] font-mono">
                      Frame {detection.frame_number}
                    </Badge>
                  </div>
                  <div className="grid grid-cols-2 gap-2 text-[10px] text-muted-foreground">
                    <div className="truncate">
                      Segment:{' '}
                      <span className="text-foreground font-medium">
                        {chainageName}
                      </span>
                    </div>
                    <div>
                      Confidence:{' '}
                      <span className="text-foreground font-medium">
                        {(detection.confidence * 100).toFixed(1)}%
                      </span>
                    </div>
                    <div className="col-span-2 font-mono bg-muted/50 p-1 rounded border">
                      GPS: {detection.latitude}, {detection.longitude}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </ScrollArea>
        </CardContent>
      </Card>

      {/* Map Modal */}
      <MapModal
        open={showMap}
        onClose={() => setShowMap(false)}
        detections={allDetections.map(({ detection }) => detection)}
        detectionType={detectionType}
      />
    </div>
  );
};

export default DetailedSummarySection;
