/**
 * POI Summary Card Component
 *
 * Displays summary statistics and high-impact categories
 */

import React from 'react';
import { Card, CardHeader, CardContent, CardTitle } from '@/components/ui/Card';
import { Badge } from '@/components/ui/Badge';
import type { POIContext } from '@/types/poi';
import { POI_CATEGORY_METADATA, getImpactLevel, IMPACT_LEVELS } from '@/types/poi';

interface POISummaryCardProps {
  poiContext: POIContext;
  onCategorySelect?: (category: string) => void;
}

export const POISummaryCard: React.FC<POISummaryCardProps> = ({
  poiContext,
  onCategorySelect
}) => {
  const highImpactCategories = poiContext.high_impact_categories || [];
  const relevantCategories = poiContext.relevant_categories || [];

  // Calculate category impact levels
  const categoryImpacts = Object.entries(poiContext.poi_detection_results)
    .map(([category, data]) => ({
      category,
      proximityScore: data.features.proximity_score,
      count: data.count,
      impactLevel: getImpactLevel(data.features.proximity_score)
    }))
    .filter(item => item.count > 0)
    .sort((a, b) => b.proximityScore - a.proximityScore);

  const detectionDate = poiContext.detection_timestamp
    ? new Date(poiContext.detection_timestamp).toLocaleDateString()
    : 'Unknown';

  const needsRefresh = poiContext.next_refresh_date
    ? new Date(poiContext.next_refresh_date) < new Date()
    : false;

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center justify-between">
          <span>POI Summary</span>
          {needsRefresh && (
            <Badge variant="warning" className="text-xs">
              Refresh Recommended
            </Badge>
          )}
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* Total POIs */}
        <div>
          <div className="text-sm text-gray-600 mb-1">Total POIs Detected</div>
          <div className="text-3xl font-bold text-gray-900">
            {poiContext.total_pois_detected}
          </div>
        </div>

        {/* Detection Info */}
        <div className="space-y-1">
          <div className="text-sm text-gray-600">Detection Date</div>
          <div className="text-sm font-medium">{detectionDate}</div>
        </div>

        {/* Detection Status */}
        <div className="space-y-1">
          <div className="text-sm text-gray-600">Status</div>
          <Badge
            variant={
              poiContext.detection_status === 'completed'
                ? 'success'
                : poiContext.detection_status === 'partial'
                ? 'warning'
                : 'destructive'
            }
          >
            {poiContext.detection_status}
          </Badge>
        </div>

        {/* Impact Categories */}
        {categoryImpacts.length > 0 && (
          <div>
            <div className="text-sm font-semibold text-gray-700 mb-2">
              Impact by Category
            </div>
            <div className="space-y-2">
              {categoryImpacts.map(({ category, count, proximityScore, impactLevel }) => {
                const metadata = POI_CATEGORY_METADATA[category];
                if (!metadata) return null;

                const impactConfig = IMPACT_LEVELS[impactLevel];

                return (
                  <div
                    key={category}
                    className="flex items-center justify-between p-2 rounded hover:bg-gray-50 cursor-pointer transition-colors"
                    onClick={() => onCategorySelect?.(category)}
                  >
                    <div className="flex items-center gap-2">
                      <span style={{ fontSize: '20px' }}>{metadata.icon}</span>
                      <div>
                        <div className="text-sm font-medium">
                          {metadata.displayName}
                        </div>
                        <div className="text-xs text-gray-600">
                          {count} {count === 1 ? 'location' : 'locations'}
                        </div>
                      </div>
                    </div>
                    <div className="text-right">
                      <Badge
                        variant={impactLevel === 'HIGH' ? 'success' : impactLevel === 'MODERATE' ? 'warning' : 'secondary'}
                        className="text-xs"
                      >
                        {impactConfig.label}
                      </Badge>
                      <div className="text-xs text-gray-600 mt-1">
                        Score: {proximityScore.toFixed(2)}
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {/* High Impact Highlights */}
        {highImpactCategories.length > 0 && (
          <div>
            <div className="text-sm font-semibold text-gray-700 mb-2">
              High Impact Factors
            </div>
            <div className="flex flex-wrap gap-2">
              {highImpactCategories.map(category => {
                const metadata = POI_CATEGORY_METADATA[category];
                if (!metadata) return null;

                return (
                  <Badge
                    key={category}
                    variant="success"
                    className="cursor-pointer"
                    onClick={() => onCategorySelect?.(category)}
                  >
                    {metadata.icon} {metadata.displayName}
                  </Badge>
                );
              })}
            </div>
          </div>
        )}

        {/* ML Features Count */}
        <div className="pt-3 border-t border-gray-200">
          <div className="text-sm text-gray-600">ML Features Generated</div>
          <div className="text-2xl font-bold text-blue-600">
            {Object.keys(poiContext.ml_features || {}).length}
          </div>
          <div className="text-xs text-gray-500 mt-1">
            Used for demand forecasting
          </div>
        </div>

        {/* Location Coordinates */}
        <div className="pt-3 border-t border-gray-200 text-xs text-gray-500">
          <div className="font-semibold mb-1">Location</div>
          <div>
            Lat: {poiContext.location.latitude.toFixed(6)}
          </div>
          <div>
            Lon: {poiContext.location.longitude.toFixed(6)}
          </div>
        </div>
      </CardContent>
    </Card>
  );
};
