/**
 * POI Category Accordion Component
 *
 * Expandable accordion showing detailed POI information by category
 */

import React, { useState } from 'react';
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from '@/components/ui/Accordion';
import { Badge } from '@/components/ui/Badge';
import { Progress } from '@/components/ui/Progress';
import type { POIContext, POICategoryData } from '@/types/poi';
import { POI_CATEGORY_METADATA, formatDistance, getImpactLevel, IMPACT_LEVELS } from '@/types/poi';

interface POICategoryAccordionProps {
  poiContext: POIContext;
  selectedCategory?: string | null;
  onCategorySelect?: (category: string | null) => void;
}

export const POICategoryAccordion: React.FC<POICategoryAccordionProps> = ({
  poiContext,
  selectedCategory,
  onCategorySelect
}) => {
  // Sort categories by proximity score (descending)
  const sortedCategories = Object.entries(poiContext.poi_detection_results)
    .filter(([_, data]) => data.count > 0)
    .sort((a, b) => b[1].features.proximity_score - a[1].features.proximity_score);

  const renderCategoryDetails = (category: string, data: POICategoryData) => {
    const { features } = data;
    const impactLevel = getImpactLevel(features.proximity_score);
    const impactConfig = IMPACT_LEVELS[impactLevel];

    return (
      <div className="space-y-4">
        {/* Summary Stats */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div>
            <div className="text-xs text-gray-600 mb-1">Total Count</div>
            <div className="text-2xl font-bold">{features.total_count}</div>
          </div>
          <div>
            <div className="text-xs text-gray-600 mb-1">Proximity Score</div>
            <div className="text-2xl font-bold text-blue-600">
              {features.proximity_score.toFixed(2)}
            </div>
          </div>
          <div>
            <div className="text-xs text-gray-600 mb-1">Nearest</div>
            <div className="text-lg font-semibold">
              {formatDistance(features.distance_to_nearest_m)}
            </div>
          </div>
          <div>
            <div className="text-xs text-gray-600 mb-1">Impact Level</div>
            <Badge
              variant={impactLevel === 'HIGH' ? 'success' : impactLevel === 'MODERATE' ? 'warning' : 'secondary'}
            >
              {impactConfig.label}
            </Badge>
          </div>
        </div>

        {/* Distance Distribution */}
        <div>
          <div className="text-sm font-semibold text-gray-700 mb-3">
            Distance Distribution
          </div>
          <div className="space-y-3">
            <div>
              <div className="flex justify-between text-xs mb-1">
                <span>0-100m (Immediate)</span>
                <span className="font-medium">{features.count_0_100m}</span>
              </div>
              <Progress
                value={(features.count_0_100m / features.total_count) * 100}
                className="h-2"
              />
            </div>
            <div>
              <div className="flex justify-between text-xs mb-1">
                <span>100-300m (Primary)</span>
                <span className="font-medium">{features.count_100_300m}</span>
              </div>
              <Progress
                value={(features.count_100_300m / features.total_count) * 100}
                className="h-2"
              />
            </div>
            <div>
              <div className="flex justify-between text-xs mb-1">
                <span>300-500m (Secondary)</span>
                <span className="font-medium">{features.count_300_500m}</span>
              </div>
              <Progress
                value={(features.count_300_500m / features.total_count) * 100}
                className="h-2"
              />
            </div>
            <div>
              <div className="flex justify-between text-xs mb-1">
                <span>500-1000m (Tertiary)</span>
                <span className="font-medium">{features.count_500_1000m}</span>
              </div>
              <Progress
                value={(features.count_500_1000m / features.total_count) * 100}
                className="h-2"
              />
            </div>
          </div>
        </div>

        {/* POI List */}
        {data.pois.length > 0 && (
          <div>
            <div className="text-sm font-semibold text-gray-700 mb-2">
              Locations ({data.pois.length})
            </div>
            <div className="max-h-64 overflow-y-auto space-y-2">
              {data.pois.map((poi, index) => (
                <div
                  key={`${poi.osm_id}-${index}`}
                  className="p-2 border border-gray-200 rounded hover:bg-gray-50 transition-colors"
                >
                  <div className="flex justify-between items-start">
                    <div className="flex-1">
                      <div className="font-medium text-sm">{poi.name}</div>
                      {poi.tags.addr_street && (
                        <div className="text-xs text-gray-600 mt-1">
                          {poi.tags.addr_street}
                          {poi.tags.addr_housenumber && ` ${poi.tags.addr_housenumber}`}
                        </div>
                      )}
                    </div>
                    {poi.distance_m !== undefined && (
                      <Badge variant="outline" className="text-xs ml-2">
                        {formatDistance(poi.distance_m)}
                      </Badge>
                    )}
                  </div>
                  {poi.zone && (
                    <div className="text-xs text-gray-500 mt-1">
                      Zone: {poi.zone.replace('_', ' ')}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Error Message */}
        {data.error && (
          <div className="p-3 bg-red-50 border border-red-200 rounded text-sm text-red-700">
            Error: {data.error}
          </div>
        )}
      </div>
    );
  };

  if (sortedCategories.length === 0) {
    return (
      <div className="text-center py-8 text-gray-500">
        No POIs detected in any category
      </div>
    );
  }

  return (
    <div className="space-y-2">
      <Accordion type="single" collapsible className="w-full">
        {sortedCategories.map(([category, data]) => {
          const metadata = POI_CATEGORY_METADATA[category];
          if (!metadata) return null;

          const impactLevel = getImpactLevel(data.features.proximity_score);
          const impactConfig = IMPACT_LEVELS[impactLevel];
          const isSelected = selectedCategory === category;

          return (
            <AccordionItem key={category} value={category}>
              <AccordionTrigger
                className={`hover:no-underline ${isSelected ? 'bg-blue-50' : ''}`}
                onClick={() => onCategorySelect?.(isSelected ? null : category)}
              >
                <div className="flex items-center justify-between w-full pr-4">
                  <div className="flex items-center gap-3">
                    <span style={{ fontSize: '24px' }}>{metadata.icon}</span>
                    <div className="text-left">
                      <div className="font-semibold">{metadata.displayName}</div>
                      <div className="text-xs text-gray-600 font-normal">
                        {data.count} {data.count === 1 ? 'location' : 'locations'}
                      </div>
                    </div>
                  </div>
                  <div className="flex items-center gap-3">
                    <Badge
                      variant={impactLevel === 'HIGH' ? 'success' : impactLevel === 'MODERATE' ? 'warning' : 'secondary'}
                    >
                      {impactConfig.label}
                    </Badge>
                    <div className="text-right">
                      <div className="text-sm font-medium">
                        Score: {data.features.proximity_score.toFixed(2)}
                      </div>
                      <div className="text-xs text-gray-600">
                        Nearest: {formatDistance(data.features.distance_to_nearest_m)}
                      </div>
                    </div>
                  </div>
                </div>
              </AccordionTrigger>
              <AccordionContent>
                <div className="pt-4 pb-2 px-2">
                  {renderCategoryDetails(category, data)}
                </div>
              </AccordionContent>
            </AccordionItem>
          );
        })}
      </Accordion>
    </div>
  );
};
