import { useState, useCallback, useEffect } from 'react';
import useEmblaCarousel from 'embla-carousel-react';
import { ExternalLink, Footprints, Bike, Train } from 'lucide-react';
import type { PropertyProperties, POIDistanceInfo, POI } from '@/types';
import { formatDuration } from '@/utils/format';

function TravelModeIcon({ mode }: { mode: string }) {
    switch (mode) {
        case 'WALK': return <Footprints className="h-3 w-3" />;
        case 'BICYCLE': return <Bike className="h-3 w-3" />;
        case 'TRANSIT': return <Train className="h-3 w-3" />;
        default: return null;
    }
}

function POIDistanceBadges({ distances }: { distances: POIDistanceInfo[] }) {
    if (!distances || distances.length === 0) return null;

    // Group by POI name
    const byPoi = new Map<string, POIDistanceInfo[]>();
    for (const d of distances) {
        const existing = byPoi.get(d.poi_name) || [];
        existing.push(d);
        byPoi.set(d.poi_name, existing);
    }

    return (
        <div className="flex flex-wrap gap-1 mt-1.5">
            {Array.from(byPoi.entries()).map(([poiName, dists]) => (
                <div key={poiName} className="inline-flex items-center gap-1 text-xs text-muted-foreground">
                    <span className="font-medium">{poiName}:</span>
                    {dists.map(d => (
                        <span key={d.travel_mode} className="inline-flex items-center gap-0.5" title={`${d.travel_mode} to ${poiName}`}>
                            <TravelModeIcon mode={d.travel_mode} />
                            {formatDuration(d.duration_seconds)}
                        </span>
                    ))}
                </div>
            ))}
        </div>
    );
}

const TRAVEL_MODES: Array<'WALK' | 'BICYCLE' | 'TRANSIT'> = ['WALK', 'BICYCLE', 'TRANSIT'];

function AllPOIDistances({ pois, distances }: { pois: POI[]; distances?: POIDistanceInfo[] }) {
    // Index distances by poi_id + travel_mode for O(1) lookup
    const distMap = new Map<string, POIDistanceInfo>();
    if (distances) {
        for (const d of distances) {
            distMap.set(`${d.poi_id}_${d.travel_mode}`, d);
        }
    }

    return (
        <div className="flex flex-wrap gap-1 mt-1.5">
            {pois.map(poi => (
                <div key={poi.id} className="inline-flex items-center gap-1 text-xs text-muted-foreground">
                    <span className="font-medium">{poi.name}:</span>
                    {TRAVEL_MODES.map(mode => {
                        const dist = distMap.get(`${poi.id}_${mode}`);
                        return (
                            <span key={mode} className="inline-flex items-center gap-0.5" title={`${mode} to ${poi.name}`}>
                                <TravelModeIcon mode={mode} />
                                {dist ? formatDuration(dist.duration_seconds) : '\u2014'}
                            </span>
                        );
                    })}
                </div>
            ))}
        </div>
    );
}

function CardCarousel({ photos, altText }: { photos: string[]; altText?: string }) {
    const [emblaRef, emblaApi] = useEmblaCarousel({ loop: true });
    const [selectedIndex, setSelectedIndex] = useState(0);

    const onSelect = useCallback(() => {
        if (!emblaApi) return;
        setSelectedIndex(emblaApi.selectedScrollSnap());
    }, [emblaApi]);

    useEffect(() => {
        if (!emblaApi) return;
        emblaApi.on('select', onSelect);
        return () => { emblaApi.off('select', onSelect); };
    }, [emblaApi, onSelect]);

    if (photos.length <= 1) {
        return (
            <img
                src={photos[0]}
                alt={altText || "Property"}
                className="w-full h-full object-cover"
                loading="lazy"
            />
        );
    }

    return (
        <div className="relative w-full h-full" onClick={e => e.stopPropagation()}>
            <div className="overflow-hidden h-full" ref={emblaRef}>
                <div className="flex h-full">
                    {photos.map((url, i) => (
                        <div key={i} className="flex-[0_0_100%] min-w-0 h-full">
                            <img
                                src={url}
                                alt={`Property photo ${i + 1}`}
                                className="w-full h-full object-cover"
                                loading="lazy"
                            />
                        </div>
                    ))}
                </div>
            </div>
            <div className="absolute bottom-1 left-0 right-0 flex justify-center gap-1">
                {photos.map((_, i) => (
                    <div
                        key={i}
                        className={`w-1 h-1 rounded-full ${
                            i === selectedIndex ? 'bg-white' : 'bg-white/40'
                        }`}
                    />
                ))}
            </div>
        </div>
    );
}

interface PropertyCardProps {
    property: PropertyProperties;
    variant?: 'compact' | 'full';
    isHighlighted?: boolean;
    avgPricePerSqm?: number;
    allPOIs?: POI[];
    onClick?: () => void;
}

export function PropertyCard({
    property,
    variant = 'compact',
    isHighlighted = false,
    avgPricePerSqm,
    allPOIs,
    onClick,
}: PropertyCardProps) {
    // BUY listings may have null numeric / date fields; coerce so renders don't throw.
    const lastSeenRaw = property.last_seen;
    const lastSeenDate = typeof lastSeenRaw === 'string' ? lastSeenRaw.split('T')[0] : null;
    const lastSeenTime = lastSeenDate ? new Date(lastSeenDate).getTime() : NaN;
    const lastSeenDays = Number.isFinite(lastSeenTime)
        ? Math.round((Date.now() - lastSeenTime) / (1000 * 60 * 60 * 24))
        : null;
    const safeNum = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
    const safeTotalPrice = safeNum(property.total_price);
    const safeQm = safeNum(property.qm);
    const safeQmprice = safeNum(property.qmprice);
    const safeRooms = safeNum(property.rooms);

    // Determine if this is a good deal
    const isGoodDeal = avgPricePerSqm && property.qmprice > 0 && property.qmprice < avgPricePerSqm * 0.9;
    const isExpensive = avgPricePerSqm && property.qmprice > avgPricePerSqm * 1.1;

    const priceIndicator = isGoodDeal
        ? { dotColor: 'bg-[var(--deal-good)]', label: 'Good deal' }
        : isExpensive
            ? { dotColor: 'bg-[var(--deal-above)]', label: 'Above avg' }
            : null;

    const handleClick = () => {
        onClick?.();
    };

    if (variant === 'compact') {
        return (
            <div
                className={`flex gap-3 p-3 rounded-lg border bg-card shadow-sm hover:shadow-md transition-shadow cursor-pointer ${
                    isHighlighted ? 'ring-2 ring-primary bg-primary/5' : ''
                }`}
                onClick={handleClick}
            >
                {/* Photo carousel */}
                <div className="w-24 h-24 rounded-md overflow-hidden flex-shrink-0 bg-muted">
                    {(property.photos?.length || property.photo_thumbnail) ? (
                        <CardCarousel
                            photos={property.photos?.length ? property.photos : [property.photo_thumbnail]}
                            altText={`${safeRooms}-bed, ${safeQm}m², £${safeTotalPrice.toLocaleString()}`}
                        />
                    ) : null}
                </div>

                {/* Details */}
                <div className="flex-1 min-w-0">
                    {/* Price */}
                    <div className="flex items-center gap-1.5">
                        <span className="text-lg font-bold tracking-tight">
                            £{safeTotalPrice.toLocaleString()}
                            {property.listing_type !== 'BUY' && (
                                <span className="text-muted-foreground font-normal text-sm">/mo</span>
                            )}
                        </span>
                        {priceIndicator && (
                            <span className={`w-2 h-2 rounded-full shrink-0 ${priceIndicator.dotColor}`} title={priceIndicator.label} />
                        )}
                        {priceIndicator && (
                            <span className="text-xs text-muted-foreground">{priceIndicator.label}</span>
                        )}
                    </div>

                    {/* Key metrics on one line */}
                    <div className="flex items-center gap-1 text-sm text-muted-foreground mt-0.5">
                        <span>{safeRooms}</span><span>bed</span>
                        <span>·</span>
                        <span>{safeQm} m²</span>
                        <span>·</span>
                        <span>£{safeQmprice}/m²</span>
                    </div>

                    {/* Agency + freshness */}
                    <div className="flex items-center gap-1 text-xs text-muted-foreground mt-1">
                        <span>{property.agency}</span>
                        {lastSeenDays !== null && (
                            <>
                                <span>·</span>
                                <span>{lastSeenDays}d ago</span>
                            </>
                        )}
                    </div>

                    {/* POI badges */}
                    <POIDistanceBadges distances={property.poi_distances || []} />
                </div>
            </div>
        );
    }

    // Full variant
    return (
        <div
            className={`rounded-lg border bg-card shadow-sm hover:shadow-md transition-shadow overflow-hidden ${
                isHighlighted ? 'ring-2 ring-primary' : ''
            }`}
            onClick={handleClick}
        >
            {/* Image section with 16:10 aspect ratio */}
            <div className="relative aspect-[16/10] bg-muted">
                {(property.photos?.length || property.photo_thumbnail) ? (
                    <CardCarousel
                        photos={property.photos?.length ? property.photos : [property.photo_thumbnail]}
                        altText={`${safeRooms}-bed, ${safeQm}m², £${safeTotalPrice.toLocaleString()}`}
                    />
                ) : null}

                {/* Overlay buttons: heart + external link */}
                <div className="absolute top-2 right-2 flex items-center gap-1.5" onClick={e => e.stopPropagation()}>
                    <a
                        href={property.url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="flex items-center justify-center w-8 h-8 rounded-full bg-black/40 backdrop-blur-sm text-white hover:bg-black/60 transition-colors"
                        title="View on Rightmove"
                    >
                        <ExternalLink className="h-4 w-4" />
                    </a>
                </div>
            </div>

            {/* Content below image */}
            <div className="p-4 space-y-2">
                {/* Price as dominant element */}
                <div className="flex items-center gap-1.5">
                    <span className="text-lg font-bold tracking-tight">
                        £{safeTotalPrice.toLocaleString()}
                        {property.listing_type !== 'BUY' && (
                            <span className="text-muted-foreground font-normal text-sm">/mo</span>
                        )}
                    </span>
                    {priceIndicator && (
                        <span className={`w-2 h-2 rounded-full shrink-0 ${priceIndicator.dotColor}`} title={priceIndicator.label} />
                    )}
                    {priceIndicator && (
                        <span className="text-xs text-muted-foreground">{priceIndicator.label}</span>
                    )}
                </div>

                {/* Key metrics on one line */}
                <div className="flex items-center gap-1 text-sm text-muted-foreground">
                    <span>{safeRooms}</span><span>bed</span>
                    <span>·</span>
                    <span>{safeQm} m²</span>
                    <span>·</span>
                    <span>£{safeQmprice}/m²</span>
                </div>

                {/* Location */}
                {property.city && (
                    <div className="text-sm font-medium">{property.city}</div>
                )}

                {/* POI travel times */}
                {allPOIs && allPOIs.length > 0 ? (
                    <AllPOIDistances pois={allPOIs} distances={property.poi_distances} />
                ) : property.poi_distances && property.poi_distances.length > 0 ? (
                    <POIDistanceBadges distances={property.poi_distances} />
                ) : null}

                {/* Agency + freshness */}
                <div className="flex items-center gap-1 text-xs text-muted-foreground">
                    <span>{property.agency}</span>
                    {lastSeenDays !== null && (
                        <>
                            <span>·</span>
                            <span>{lastSeenDays}d ago</span>
                        </>
                    )}
                </div>
            </div>
        </div>
    );
}
