import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { RideCoasterStat } from "@/types/database";
import { TrendingUp } from "lucide-react";
import { useUnitPreferences } from "@/hooks/useUnitPreferences";
import { convertValueFromMetric, detectUnitType, getMetricUnit, getDisplayUnit } from "@/lib/units";

interface CoasterStatisticsProps {
  statistics?: RideCoasterStat[];
}

export const CoasterStatistics = ({ statistics }: CoasterStatisticsProps) => {
  const { preferences } = useUnitPreferences();
  
  if (!statistics || statistics.length === 0) {
    return null;
  }

  const getDisplayValue = (stat: RideCoasterStat) => {
    if (!stat.unit) {
      return stat.stat_value.toLocaleString();
    }

    const unitType = detectUnitType(stat.unit);
    if (unitType === 'unknown') {
      return `${stat.stat_value.toLocaleString()} ${stat.unit}`;
    }

    // stat.unit is the metric unit stored in DB (e.g., "km/h")
    // Get the target display unit based on user preference (e.g., "mph" for imperial)
    const displayUnit = getDisplayUnit(stat.unit, preferences.measurement_system);
    
    // Convert from metric (stat.unit) to display unit
    const convertedValue = convertValueFromMetric(
      stat.stat_value,
      displayUnit,  // Target unit (mph, ft, in)
      stat.unit     // Source metric unit (km/h, m, cm)
    );
    
    return `${convertedValue.toLocaleString()} ${displayUnit}`;
  };

  // Group stats by category
  const groupedStats = statistics.reduce((acc, stat) => {
    const category = stat.category || 'General';
    if (!acc[category]) {
      acc[category] = [];
    }
    acc[category].push(stat);
    return acc;
  }, {} as Record<string, RideCoasterStat[]>);

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <TrendingUp className="h-5 w-5" />
          Coaster Statistics
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="space-y-6">
          {Object.entries(groupedStats).map(([category, stats]) => (
            <div key={category}>
              <h3 className="text-sm font-semibold mb-3 text-muted-foreground uppercase tracking-wide">
                {category}
              </h3>
              <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 gap-3">
                {stats
                  .sort((a, b) => a.display_order - b.display_order)
                  .map((stat) => (
                    <div
                      key={stat.id}
                      className="flex justify-between items-center p-3 rounded-lg bg-muted/50"
                    >
                      <div className="flex flex-col">
                        <span className="text-sm font-medium">{stat.stat_name}</span>
                        {stat.description && (
                          <span className="text-xs text-muted-foreground">
                            {stat.description}
                          </span>
                        )}
                      </div>
                      <span className="text-sm font-semibold">
                        {getDisplayValue(stat)}
                      </span>
                    </div>
                  ))}
              </div>
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  );
};
