import { useState, useCallback, useEffect } from 'react';
import { X, Heart, ArrowUp, Undo2, ArrowLeft } from 'lucide-react';
import { Button } from './ui/button';
import { SwipeCard } from './SwipeCard';
import type { PropertyFeature, DecisionType } from '@/types';

interface SwipeReviewModeProps {
  features: PropertyFeature[];
  onDecide: (listingId: number, decision: DecisionType, listingType?: 'RENT' | 'BUY') => void;
  onClear: (listingId: number, listingType?: 'RENT' | 'BUY') => void;
  onClose: () => void;
  onSelectListing?: (listingId: number) => void;
  getDecision: (listingId: number, listingType?: string) => DecisionType | undefined;
}

interface HistoryEntry {
  index: number;
  listingId: number;
  listingType: string;
  action: 'liked' | 'disliked' | 'skipped';
}

function getListingId(feature: PropertyFeature): number {
  const parts = feature.properties.url.split('/');
  return parseInt(parts[parts.length - 1], 10);
}

function getListingType(feature: PropertyFeature): 'RENT' | 'BUY' {
  return feature.properties.listing_type === 'BUY' ? 'BUY' : 'RENT';
}

export function SwipeReviewMode({
  features,
  onDecide,
  onClear,
  onClose,
  onSelectListing,
  getDecision,
}: SwipeReviewModeProps) {
  // Filter to only undecided features
  const undecided = features.filter((f) => {
    const id = getListingId(f);
    const type = getListingType(f);
    return getDecision(id, type) === undefined;
  });

  const [currentIndex, setCurrentIndex] = useState(0);
  const [history, setHistory] = useState<HistoryEntry[]>([]);

  const handleSwipe = useCallback(
    (direction: 'left' | 'right' | 'up') => {
      const feature = undecided[currentIndex];
      if (!feature) return;

      const listingId = getListingId(feature);
      const listingType = getListingType(feature);

      let action: HistoryEntry['action'];
      if (direction === 'right') {
        action = 'liked';
        onDecide(listingId, 'liked', listingType);
      } else if (direction === 'left') {
        action = 'disliked';
        onDecide(listingId, 'disliked', listingType);
      } else {
        action = 'skipped';
      }

      setHistory((prev) => [...prev, { index: currentIndex, listingId, listingType, action }]);
      setCurrentIndex((prev) => prev + 1);
    },
    [currentIndex, undecided, onDecide],
  );

  const handleUndo = useCallback(() => {
    const lastEntry = history[history.length - 1];
    if (!lastEntry) return;

    if (lastEntry.action !== 'skipped') {
      onClear(lastEntry.listingId, lastEntry.listingType as 'RENT' | 'BUY');
    }
    setHistory((prev) => prev.slice(0, -1));
    setCurrentIndex((prev) => prev - 1);
  }, [history, onClear]);

  // Keyboard shortcuts
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'ArrowRight') handleSwipe('right');
      else if (e.key === 'ArrowLeft') handleSwipe('left');
      else if (e.key === 'ArrowUp') handleSwipe('up');
      else if ((e.ctrlKey || e.metaKey) && e.key === 'z') handleUndo();
      else if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [handleSwipe, handleUndo, onClose]);

  const isFinished = currentIndex >= undecided.length;

  return (
    <div className="fixed inset-0 z-50 bg-background flex flex-col">
      {/* Header */}
      <div className="flex items-center justify-between px-4 py-3 border-b">
        <Button variant="ghost" size="sm" onClick={onClose}>
          <ArrowLeft className="h-4 w-4 mr-1" /> Back
        </Button>
        <span className="text-sm text-muted-foreground">
          {Math.min(currentIndex + 1, undecided.length)} / {undecided.length}
        </span>
        <div className="w-16" />
      </div>

      {/* Card stack */}
      <div className="flex-1 relative overflow-hidden flex items-start justify-center pt-4">
        {isFinished ? (
          <div className="flex items-center justify-center h-full">
            <div className="text-center p-8">
              <p className="text-xl font-semibold mb-2">All done!</p>
              <p className="text-muted-foreground mb-4">
                You've reviewed all {undecided.length} properties.
              </p>
              <Button onClick={onClose}>Back to listings</Button>
            </div>
          </div>
        ) : (
          <div className="relative w-full max-w-md h-full">
            {undecided.slice(currentIndex, currentIndex + 3).map((feature, i) => (
              <SwipeCard
                key={feature.properties.url}
                feature={feature}
                onSwipe={handleSwipe}
                onTap={() => onSelectListing?.(getListingId(feature))}
                isTop={i === 0}
                stackIndex={i}
              />
            ))}
          </div>
        )}
      </div>

      {/* Action buttons */}
      {!isFinished && (
        <div className="flex items-center justify-center gap-6 py-6 px-4">
          <Button
            variant="outline"
            size="lg"
            className="rounded-full h-14 w-14 border-red-300 text-red-500 hover:bg-red-50"
            onClick={() => handleSwipe('left')}
          >
            <X className="h-6 w-6" />
          </Button>

          <Button
            variant="outline"
            size="sm"
            className="rounded-full h-10 w-10"
            onClick={handleUndo}
            disabled={history.length === 0}
          >
            <Undo2 className="h-4 w-4" />
          </Button>

          <Button
            variant="outline"
            size="sm"
            className="rounded-full h-10 w-10"
            onClick={() => handleSwipe('up')}
          >
            <ArrowUp className="h-4 w-4" />
          </Button>

          <Button
            variant="outline"
            size="lg"
            className="rounded-full h-14 w-14 border-green-300 text-green-500 hover:bg-green-50"
            onClick={() => handleSwipe('right')}
          >
            <Heart className="h-6 w-6" />
          </Button>
        </div>
      )}
    </div>
  );
}
