import { AlertCircle, Loader2, MapPin, RefreshCw, Save, Sparkles, Trash2 } from 'lucide-react';
import React from 'react';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Progress } from '@/components/ui/progress';
import { Skeleton } from '@/components/ui/skeleton';
import { cn } from '@/lib/utils';

/**
 * Yükleme Durumları Enum
 */
export enum LoadingState {
  IDLE = 'IDLE',
  LOADING_TRIP = 'LOADING_TRIP',
  LOADING_PLACES = 'LOADING_PLACES',
  SAVING_TRIP = 'SAVING_TRIP',
  SAVING_PLACE = 'SAVING_PLACE',
  DELETING = 'DELETING',
  OPTIMIZING = 'OPTIMIZING',
  ERROR = 'ERROR'
}

interface LoadingProps {
  state: LoadingState;
  message?: string;
  progress?: number;
  errorDetails?: string;
  className?: string;
  showProgress?: boolean;
}

/**
 * Durum Mesajları (Türkçe)
 */
const STATE_MESSAGES: Record<LoadingState, string> = {
  [LoadingState.IDLE]: '',
  [LoadingState.LOADING_TRIP]: 'Gezi planı yükleniyor...',
  [LoadingState.LOADING_PLACES]: 'Yerler aranıyor...',
  [LoadingState.SAVING_TRIP]: 'Gezi planı kaydediliyor...',
  [LoadingState.SAVING_PLACE]: 'Yer kaydediliyor...',
  [LoadingState.DELETING]: 'Siliniyor...',
  [LoadingState.OPTIMIZING]: 'Rota optimize ediliyor...',
  [LoadingState.ERROR]: 'Bir hata oluştu.'
};

/**
 * Durum İkonları
 */
const STATE_ICONS: Record<LoadingState, React.ReactNode> = {
  [LoadingState.IDLE]: null,
  [LoadingState.LOADING_TRIP]: <Loader2 className="h-5 w-5 animate-spin" />,
  [LoadingState.LOADING_PLACES]: <MapPin className="h-5 w-5 animate-pulse" />,
  [LoadingState.SAVING_TRIP]: <Save className="h-5 w-5 animate-bounce" />,
  [LoadingState.SAVING_PLACE]: <Save className="h-5 w-5 animate-pulse" />,
  [LoadingState.DELETING]: <Trash2 className="h-5 w-5 text-destructive" />,
  [LoadingState.OPTIMIZING]: <Sparkles className="h-5 w-5 text-primary animate-pulse" />,
  [LoadingState.ERROR]: <AlertCircle className="h-5 w-5 text-destructive" />
};

/**
 * Küçük Yükleme Göstergesi (Satır İçi Kullanım İçin)
 */
export const LoadingIndicator: React.FC<LoadingProps> = ({ 
  state, 
  message, 
  className 
}) => {
  if (state === LoadingState.IDLE) return null;

  return (
    <div className={cn("flex items-center gap-2 text-sm font-medium text-muted-foreground", className)}>
      {STATE_ICONS[state]}
      <span>{message || STATE_MESSAGES[state]}</span>
    </div>
  );
};

/**
 * Tam Sayfa veya Konteynır Üzeri Yükleme Katmanı
 */
export const LoadingOverlay: React.FC<LoadingProps> = ({ 
  state, 
  message, 
  progress, 
  showProgress, 
  errorDetails,
  className 
}) => {
  if (state === LoadingState.IDLE) return null;

  if (state === LoadingState.ERROR) {
    return (
      <div className={cn("p-4", className)}>
        <Alert variant="destructive">
          <AlertCircle className="h-4 w-4" />
          <AlertTitle>Hata</AlertTitle>
          <AlertDescription>
            {message || STATE_MESSAGES[state]}
            {errorDetails && <p className="mt-2 text-xs opacity-80">{errorDetails}</p>}
          </AlertDescription>
        </Alert>
      </div>
    );
  }

  return (
    <div 
      className={cn(
        "absolute inset-0 z-50 flex flex-col items-center justify-center bg-background/80 backdrop-blur-sm transition-all duration-300",
        className
      )}
      aria-live="polite"
      role="status"
    >
      <div className="flex flex-col items-center gap-4 max-w-xs text-center">
        <div className="rounded-full bg-primary/10 p-4">
          {/* @ts-ignore */}
          {React.cloneElement(STATE_ICONS[state] as React.ReactElement, { className: "h-8 w-8 animate-spin" })}
        </div>
        
        <div className="space-y-1">
          <h3 className="font-semibold text-foreground">
            {message || STATE_MESSAGES[state]}
          </h3>
          <p className="text-xs text-muted-foreground">
            Lütfen bekleyin, bu işlem biraz zaman alabilir.
          </p>
        </div>

        {(showProgress || progress !== undefined) && (
          <div className="w-full mt-4 space-y-2">
            <Progress value={progress} className="h-2 w-full" />
            {progress !== undefined && (
              <span className="text-xs font-medium text-primary">%{Math.round(progress)} Tamamlandı</span>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

/**
 * Gezi Özeti Skeleton
 */
export const TripSkeleton = () => (
  <div className="space-y-4 w-full">
    <Skeleton className="h-8 w-3/4 rounded-md" />
    <div className="flex gap-2">
      <Skeleton className="h-4 w-24 rounded-full" />
      <Skeleton className="h-4 w-24 rounded-full" />
    </div>
    <Skeleton className="h-[200px] w-full rounded-xl" />
  </div>
);

/**
 * Yer Kartı Skeleton
 */
export const PlaceSkeleton = () => (
  <div className="flex gap-4 p-4 border rounded-xl bg-card shadow-sm">
    <Skeleton className="h-24 w-24 rounded-lg shrink-0" />
    <div className="flex-1 space-y-2">
      <Skeleton className="h-5 w-1/2" />
      <Skeleton className="h-4 w-full" />
      <Skeleton className="h-4 w-3/4" />
      <div className="flex gap-2 pt-2">
        <Skeleton className="h-8 w-20" />
        <Skeleton className="h-8 w-20" />
      </div>
    </div>
  </div>
);

/**
 * Zaman Çizelgesi (Timeline) Skeleton
 */
export const TimelineSkeleton = () => (
  <div className="space-y-8 py-4">
    {[1, 2, 3].map((i) => (
      <div key={i} className="relative pl-8 border-l-2 border-muted ml-4">
        <div className="absolute -left-[9px] top-0 h-4 w-4 rounded-full bg-muted border-2 border-background" />
        <div className="space-y-3">
          <div className="flex items-center gap-2">
            <Skeleton className="h-4 w-16" />
            <Skeleton className="h-4 w-32" />
          </div>
          <PlaceSkeleton />
        </div>
      </div>
    ))}
  </div>
);

/**
 * Optimizasyon İlerleme Çubuğu
 */
export const OptimizationProgress: React.FC<{ progress: number }> = ({ progress }) => (
  <div className="w-full space-y-3 p-6 bg-primary/5 rounded-2xl border border-primary/10">
    <div className="flex justify-between items-center">
      <div className="flex items-center gap-2">
        <RefreshCw className="h-4 w-4 text-primary animate-spin" />
        <span className="text-sm font-semibold text-primary">Rota Optimize Ediliyor</span>
      </div>
      <span className="text-xs font-bold text-primary">%{progress}</span>
    </div>
    <Progress value={progress} className="h-2.5 bg-primary/20" />
    <p className="text-[11px] text-muted-foreground italic text-center">
      En iyi rota, trafik ve mesafe hesaplanıyor...
    </p>
  </div>
);

export default {
  LoadingIndicator,
  LoadingOverlay,
  TripSkeleton,
  PlaceSkeleton,
  TimelineSkeleton,
  OptimizationProgress,
  LoadingState
};
