import { Clock, Plus, Sparkles } from 'lucide-react';
import React, { useMemo } from 'react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';

interface Suggestion {
  placeId: string;
  name: string;
  type: string;
  reason: string;
  suggestedTimeBlock: 'dawn' | 'morning' | 'afternoon' | 'evening';
  image?: string;
  description?: string;
}

interface AISuggestionsProps {
  suggestions: Suggestion[];
  onAddSuggestion: (placeId: string, suggestedTimeBlock: string) => void;
  dayNumber: number;
}

const timeBlockLabels: Record<string, string> = {
  dawn: '🌅 Gün Doğumu',
  morning: '☀️ Sabah',
  afternoon: '🌤️ Öğle',
  evening: '🌆 Akşam',
};

const typeLabels: Record<string, string> = {
  museum: 'Müze',
  historical: 'Tarihi Yer',
  viewpoint: 'Manzara',
  restaurant: 'Restoran',
  cafe: 'Kafe',
  activity: 'Aktivite',
  shopping: 'Alışveriş',
  hotel: 'Otel',
  attraction: 'Turistik Yer',
  valley: 'Vadi',
};

const categoryIcons: Record<string, string> = {
  attractions: '🏛️',
  food: '🍽️',
  activities: '🎯',
  viewpoints: '📸',
};

export const AISuggestions: React.FC<AISuggestionsProps> = ({
  suggestions,
  onAddSuggestion,
  dayNumber,
}) => {
  if (!suggestions || suggestions.length === 0) return null;

  // Group suggestions by category
  const groupedSuggestions = useMemo(() => {
    const groups = {
      attractions: [] as Suggestion[],
      food: [] as Suggestion[],
      activities: [] as Suggestion[],
      viewpoints: [] as Suggestion[],
    };

    suggestions.forEach((suggestion) => {
      const type = suggestion.type.toLowerCase();
      if (type.includes('restaurant') || type.includes('cafe')) {
        groups.food.push(suggestion);
      } else if (type.includes('activity') || type.includes('adventure') || type.includes('tour')) {
        groups.activities.push(suggestion);
      } else if (type.includes('viewpoint') || type.includes('panorama') || type.includes('scenic')) {
        groups.viewpoints.push(suggestion);
      } else {
        groups.attractions.push(suggestion);
      }
    });

    return groups;
  }, [suggestions]);

  const totalCount = suggestions.length;
  const hasMultipleCategories = Object.values(groupedSuggestions).filter(g => g.length > 0).length > 1;

  const renderSuggestionCard = (suggestion: Suggestion, index: number) => (
    <div 
      key={`${suggestion.placeId}-${index}`}
      className="flex gap-3 p-3 rounded-xl bg-background border hover:border-primary/50 transition-all group"
    >
      <div className="flex-1 min-w-0">
        <div className="flex items-start justify-between gap-2 mb-1">
          <h4 className="font-semibold text-sm truncate">{suggestion.name}</h4>
          <Badge variant="secondary" className="shrink-0 text-xs">
            {typeLabels[suggestion.type] || suggestion.type}
          </Badge>
        </div>
        
        <p className="text-xs text-muted-foreground mb-2 line-clamp-2">
          {suggestion.reason}
        </p>
        
        <div className="flex items-center gap-2">
          <Clock className="h-3 w-3 text-primary" />
          <span className="text-xs text-primary font-medium">
            {timeBlockLabels[suggestion.suggestedTimeBlock]}
          </span>
        </div>
      </div>
      
      <div className="flex flex-col justify-center shrink-0">
        <Button
          size="sm"
          className="h-8 px-3 text-xs"
          onClick={() => onAddSuggestion(suggestion.placeId, suggestion.suggestedTimeBlock)}
        >
          <Plus className="h-3 w-3 mr-1" />
          Ekle
        </Button>
      </div>
    </div>
  );

  return (
    <Card className="border-primary/20 bg-gradient-to-br from-primary/5 to-transparent">
      <CardContent className="p-4">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <Sparkles className="h-5 w-5 text-primary" />
            <h3 className="font-bold text-base">AI Önerileri - Gün {dayNumber}</h3>
          </div>
          <Badge variant="outline" className="text-xs">
            {totalCount} öneri
          </Badge>
        </div>
        
        {hasMultipleCategories ? (
          <Tabs defaultValue="all" className="w-full">
            <div className="overflow-x-auto pb-2 -mx-2 px-2 scrollbar-none">
              <TabsList className="inline-flex w-max min-w-full md:grid md:w-full md:grid-cols-5 mb-2 h-auto p-1 bg-muted/50">
                <TabsTrigger value="all" className="text-[10px] sm:text-xs py-1.5 px-3">
                  Tümü ({totalCount})
                </TabsTrigger>
                {groupedSuggestions.attractions.length > 0 && (
                  <TabsTrigger value="attractions" className="text-[10px] sm:text-xs py-1.5 px-3">
                    {categoryIcons.attractions} ({groupedSuggestions.attractions.length})
                  </TabsTrigger>
                )}
                {groupedSuggestions.food.length > 0 && (
                  <TabsTrigger value="food" className="text-[10px] sm:text-xs py-1.5 px-3">
                    {categoryIcons.food} ({groupedSuggestions.food.length})
                  </TabsTrigger>
                )}
                {groupedSuggestions.activities.length > 0 && (
                  <TabsTrigger value="activities" className="text-[10px] sm:text-xs py-1.5 px-3">
                    {categoryIcons.activities} ({groupedSuggestions.activities.length})
                  </TabsTrigger>
                )}
                {groupedSuggestions.viewpoints.length > 0 && (
                  <TabsTrigger value="viewpoints" className="text-[10px] sm:text-xs py-1.5 px-3">
                    {categoryIcons.viewpoints} ({groupedSuggestions.viewpoints.length})
                  </TabsTrigger>
                )}
              </TabsList>
            </div>
            
            <TabsContent value="all" className="space-y-3 max-h-[500px] overflow-y-auto pr-2">
              {suggestions.map((suggestion, index) => renderSuggestionCard(suggestion, index))}
            </TabsContent>
            
            {groupedSuggestions.attractions.length > 0 && (
              <TabsContent value="attractions" className="space-y-3 max-h-[500px] overflow-y-auto pr-2">
                {groupedSuggestions.attractions.map((suggestion, index) => renderSuggestionCard(suggestion, index))}
              </TabsContent>
            )}
            
            {groupedSuggestions.food.length > 0 && (
              <TabsContent value="food" className="space-y-3 max-h-[500px] overflow-y-auto pr-2">
                {groupedSuggestions.food.map((suggestion, index) => renderSuggestionCard(suggestion, index))}
              </TabsContent>
            )}
            
            {groupedSuggestions.activities.length > 0 && (
              <TabsContent value="activities" className="space-y-3 max-h-[500px] overflow-y-auto pr-2">
                {groupedSuggestions.activities.map((suggestion, index) => renderSuggestionCard(suggestion, index))}
              </TabsContent>
            )}
            
            {groupedSuggestions.viewpoints.length > 0 && (
              <TabsContent value="viewpoints" className="space-y-3 max-h-[500px] overflow-y-auto pr-2">
                {groupedSuggestions.viewpoints.map((suggestion, index) => renderSuggestionCard(suggestion, index))}
              </TabsContent>
            )}
          </Tabs>
        ) : (
          <div className="space-y-3 max-h-[500px] overflow-y-auto pr-2">
            {suggestions.map((suggestion, index) => renderSuggestionCard(suggestion, index))}
          </div>
        )}
      </CardContent>
    </Card>
  );
};
