import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { Clock, GripVertical, Lock, MoreHorizontal, Trash2 } from 'lucide-react';
import React from 'react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { LazyImage } from '@/components/ui/lazy-image';
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle, SheetTrigger } from '@/components/ui/sheet';
import { Textarea } from '@/components/ui/textarea';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { isBalloonActivity } from '@/lib/time-blocks';
import { cn } from '@/lib/utils';

interface TimelinePlaceProps {
  place: any;
  isHovered: boolean;
  isSelected: boolean;
  isHighlighted?: boolean;
  onPlaceClick: (id: string) => void;
  onPlaceHover: (id: string | null) => void;
  onRemove: (tripPlaceId: string, name: string, placeType?: string) => void;
  placeRefs: React.MutableRefObject<Map<string, HTMLDivElement>>;
  orderNumber: number;
}

export const TimelinePlace: React.FC<TimelinePlaceProps> = ({
  place,
  isHovered,
  isSelected,
  isHighlighted = false,
  onPlaceClick,
  onPlaceHover,
  onRemove,
  placeRefs,
  orderNumber,
}) => {
  // Sabit saatli etkinlikler için sürükleme devre dışı
  const isTimeFixed = place.is_time_fixed || false;
  
  // Balon aktivitesi kontrolü
  const isBalloon = isBalloonActivity(place);
  
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ 
    id: place.tripPlaceId,
    disabled: isTimeFixed || isBalloon, // Sabit saatli ve balon etkinlikleri sürüklenemez
  });

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
  };

  const isActive = isHovered || isSelected;

  return (
    <Sheet>
      <SheetTrigger asChild>
        <div
          ref={(el) => {
            setNodeRef(el);
            if (el) placeRefs.current.set(place.id, el);
          }}
          style={style}
          className={cn(
            "flex gap-2 sm:gap-3 p-3 sm:p-4 rounded-xl bg-card border-2 shadow-sm group hover:border-primary/40 transition-all duration-200 cursor-pointer relative",
            isActive && "border-primary ring-2 ring-primary/20 shadow-md",
            isHighlighted && "border-primary ring-4 ring-primary/40 shadow-lg animate-pulse-glow",
            isDragging && "shadow-lg ring-4 ring-primary/30 scale-105"
          )}
          onClick={() => onPlaceClick(place.id)}
          onMouseEnter={() => onPlaceHover(place.id)}
          onMouseLeave={() => onPlaceHover(null)}
        >
          {/* Order Number Badge */}
          <div className="absolute -left-2 sm:-left-3 -top-2 sm:-top-3 w-6 h-6 sm:w-8 sm:h-8 rounded-full bg-primary text-primary-foreground border-2 sm:border-4 border-background flex items-center justify-center text-xs sm:text-sm font-bold shadow-md">
            {orderNumber}
          </div>

          {/* Drag Handle - Sabit saatli ve balon etkinlikleri için kilit ikonu */}
          <div
            {...((isTimeFixed || isBalloon) ? {} : attributes)}
            {...((isTimeFixed || isBalloon) ? {} : listeners)}
            className={cn(
              "flex items-center touch-none self-start mt-1",
              (isTimeFixed || isBalloon)
                ? "text-muted-foreground/50 cursor-not-allowed" 
                : "cursor-grab active:cursor-grabbing text-muted-foreground/30 group-hover:text-muted-foreground"
            )}
            title={(isTimeFixed || isBalloon) ? "Sabit saatli etkinlik - sürüklenemez" : "Sürükle"}
            onClick={(e) => e.stopPropagation()}
          >
            {(isTimeFixed || isBalloon) ? (
              <div className="flex items-center gap-1">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
                  <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
                </svg>
              </div>
            ) : (
              <GripVertical className="h-5 w-5" />
            )}
          </div>

          {/* Place Image */}
          <LazyImage 
            src={place.img} 
            alt={place.name} 
            className="w-12 h-12 sm:w-16 sm:h-16 rounded-lg object-cover bg-muted shrink-0" 
          />

          {/* Place Info */}
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-1 sm:gap-2 mb-1">
              <h5 className="font-bold text-sm sm:text-base truncate">{place.name}</h5>
              {isBalloon && (
                <Badge variant="secondary" className="text-[9px] sm:text-[10px] px-1 sm:px-2 py-0.5 bg-gradient-to-r from-amber-500/20 to-orange-500/20 text-amber-700 dark:text-amber-300 border-amber-500/30 shrink-0">
                  🌅 Gün Doğumu
                </Badge>
              )}
              {isTimeFixed && !isBalloon && (
                <Badge variant="secondary" className="text-[9px] sm:text-[10px] px-1 sm:px-2 py-0.5 bg-amber-500/10 text-amber-700 dark:text-amber-400 border-amber-500/20 shrink-0">
                  🔒 Sabit Saat
                </Badge>
              )}
            </div>
            <div className="flex items-center gap-1 sm:gap-2 text-xs text-muted-foreground mb-1 flex-wrap">
              <Badge variant="secondary" className="text-[9px] sm:text-[10px] px-1 sm:px-1.5 py-0 shrink-0">
                {place.type}
              </Badge>
              {place.duration && (
                <div className="flex items-center gap-1 shrink-0">
                  <Clock className="h-3 w-3" />
                  <span className="text-[10px] sm:text-xs">{place.duration}</span>
                </div>
              )}
            </div>
            {/* Balon için özel saat gösterimi */}
            {isBalloon && (
              <div className="text-xs sm:text-sm font-semibold text-amber-600 dark:text-amber-400 truncate">
                ⏰ 05:00 - 08:00 (Hava durumuna göre değişebilir)
              </div>
            )}
            {/* Sabit saatli etkinlikler için başlangıç-bitiş saati göster */}
            {isTimeFixed && !isBalloon && place.fixed_start_time && place.fixed_end_time && (
              <div className="text-xs sm:text-sm font-semibold text-amber-600 dark:text-amber-400">
                ⏰ {place.fixed_start_time.substring(0, 5)} - {place.fixed_end_time.substring(0, 5)}
              </div>
            )}
            {/* Normal etkinlikler için tahmini saat göster */}
            {!isTimeFixed && !isBalloon && place.startTime && place.endTime && (
              <div className="text-xs sm:text-sm font-semibold text-primary">
                {place.startTime} - {place.endTime}
              </div>
            )}
          </div>

          {/* More Options */}
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button 
                variant="ghost" 
                size="icon" 
                className="h-7 w-7 sm:h-8 sm:w-8 text-muted-foreground hover:text-foreground shrink-0 self-start z-20"
                onClick={(e) => {
                  e.stopPropagation();
                  e.preventDefault();
                }}
              >
                <MoreHorizontal className="h-3 w-3 sm:h-4 sm:w-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-40" onClick={(e) => e.stopPropagation()}>
              <DropdownMenuItem 
                className="text-destructive focus:text-destructive focus:bg-destructive/10"
                onClick={(e) => {
                  e.stopPropagation();
                  onRemove(place.tripPlaceId, place.name, place.type);
                }}
              >
                <Trash2 className="h-4 w-4 mr-2" />
                Seyahatten Kaldır
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </SheetTrigger>

      {/* Place Details Sheet */}
      <SheetContent>
        <SheetHeader className="space-y-4">
          <LazyImage 
            src={place.img} 
            alt={place.name} 
            className="w-full h-48 object-cover rounded-xl -mt-6 -mx-6 mb-2" 
            style={{ width: 'calc(100% + 48px)' }} 
            priority={true}
          />
          <SheetTitle className="text-2xl">{place.name}</SheetTitle>
          <div className="flex items-center gap-2">
            <Badge className="bg-primary/10 text-primary border-none">
              {place.rating} ★
            </Badge>
            <span className="text-sm text-muted-foreground">{place.type}</span>
          </div>
          <SheetDescription>
            {place.description}
          </SheetDescription>
        </SheetHeader>
        <div className="mt-8 space-y-6">
          <div className="space-y-2">
            <label className="text-sm font-semibold">Tahmini Süre</label>
            <Input defaultValue={place.duration} />
          </div>
          <div className="space-y-2">
            <label className="text-sm font-semibold">Notlar</label>
            <Textarea 
              placeholder="Buraya gitmek için notlarınızı yazın..." 
              className="h-32" 
            />
          </div>
          <div className="flex flex-col gap-2 pt-4">
            <Button className="w-full rounded-full">
              Değişiklikleri Kaydet
            </Button>
            <Button
              variant="ghost"
              className="w-full text-destructive hover:bg-destructive/10 hover:text-destructive rounded-full"
              onClick={() => onRemove(place.tripPlaceId, place.name, place.type)}
            >
              Seyahatten Kaldır
            </Button>
          </div>
        </div>
      </SheetContent>
    </Sheet>
  );
};
