import React, { useState } from 'react';
import { Head, Link } from '@inertiajs/react';
import { router } from '@inertiajs/react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import {
    Search,
    Star,
    MapPin,
    Sparkles,
    Navigation,
    Loader2,
    Heart,
    MessageCircle,
    Users,
    Calendar,
    Clock,
    ExternalLink
} from 'lucide-react';
import AppLayout from '@/layouts/app-layout';
import ExperienceCard from '@/components/experience-card';
import PointOfInterestCard from '@/components/point-of-interest-card';

interface Experience {
    id: number;
    content: string;
    location: string;
    latitude?: string;
    longitude?: string;
    image_url?: string;
    time_ago?: string;
    engagement_rate: number;
    is_featured: boolean;
    user?: {
        name?: string;
        id: number;
    };
    stats?: {
        likes_count: number;
        comments_count: number;
        shares_count: number;
        views_count: number;
        total_engagement: number;
    };
}

interface PointOfInterest {
    id: number;
    name: string;
    description: string;
    location: string;
    latitude?: string;
    longitude?: string;
    image_url?: string;
    time_ago?: string;
    is_featured?: boolean;
    category?: {
        name: string;
    };
    engagement?: string;
}

interface SearchTerms {
    locations: string[];
    activities: string[];
    keywords: string[];
}

interface TripPlannerProps {
    auth?: any;
}

// Custom Markdown Renderer Component
const MarkdownRenderer = ({ content }: { content: string }) => {
    const processMarkdown = (text: string) => {
        return text
            .replace(/^## (.*$)/gm, '<h2 class="text-xl font-bold text-gray-900 dark:text-gray-100 mt-6 mb-3">$1</h2>')
            .replace(/^\* \*\*(.*?)\*\*:/gm, '<div class="font-semibold text-gray-800 dark:text-gray-200 mt-4 mb-1">$1:</div>')
            .replace(/\*\*(.*?)\*\*/g, '<strong class="font-semibold text-gray-900 dark:text-gray-100">$1</strong>')
            .replace(/^- (.*$)/gm, '<li class="ml-4 list-disc text-gray-700 dark:text-gray-300">$1</li>')
            .replace(/\n\n/g, '<br><br>')
            .replace(/\n/g, '<br>');
    };

    return (
        <div
            className="prose prose-sm max-w-none text-gray-700 dark:text-gray-300"
            dangerouslySetInnerHTML={{ __html: processMarkdown(content) }}
        />
    );
};

const TripPlanner = ({ auth }: TripPlannerProps) => {
    const [description, setDescription] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [recommendations, setRecommendations] = useState<string | null>(null);
    const [experiences, setExperiences] = useState<Experience[]>([]);
    const [pointsOfInterest, setPointsOfInterest] = useState<PointOfInterest[]>([]);
    const [searchTerms, setSearchTerms] = useState<SearchTerms | null>(null);
    const [error, setError] = useState<string | null>(null);

    const t = (key: string) => {
        const translations: { [key: string]: string } = {
            'Trip Planner': 'Planificator de Călătorie',
            'AI Trip Planner': 'Planificator AI de Călătorie',
            'Plan your perfect trip': 'Planifică-ți călătoria perfectă',
            'Describe your dream trip and let AI create personalized recommendations for authentic experiences and fascinating points of interest.': 'Descrie-ne călătoria ta visată și lasă AI-ul să îți creeze recomandări personalizate pentru experiențe autentice și puncte de interes fascinante.',
            'Describe your ideal trip': 'Descrie-ți călătoria ideală',
            'Tell us about your travel preferences': 'Spune-ne despre preferințele tale de călătorie',
            'Example: I want to discover authentic culinary experiences and visit interesting museums in Bucharest. I\'m interested in interactive workshops and local restaurants...': 'Exemple: Vreau să descopăr experiențe culinare autentice și să vizitez muzee interesante în București. Sunt interesat de ateliere interactive și restaurante locale...',
            'Minimum 10 characters, maximum 1000 characters': 'Minimum 10 caractere, maximum 1000 caractere',
            'Generating recommendations...': 'Generez recomandări...',
            'Generate trip plan': 'Generează planul de călătorie',
            'Ideas for inspiration': 'Idei pentru inspirație',
            'I want to discover authentic culinary experiences and visit interesting museums in Bucharest.': 'Vreau să descopăr experiențe culinare autentice și să vizitez muzee interesante în București.',
            'I\'m planning a cultural trip with art galleries and traditional workshops in Romania.': 'Planific o călătorie culturală cu galerii de artă și ateliere tradiționale în România.',
            'I\'m looking for adventure activities and local restaurants near Bucharest.': 'Caut activități de aventură și restaurante locale în apropierea Bucureștiului.',
            'I want to explore historical points of interest and take part in interactive experiences.': 'Doresc să explorez puncte de interes istorice și să iau parte la experiențe interactive.',
            'Error': 'Eroare',
            'Your personalized recommendations': 'Recomandările tale personalizate',
            'Explore experiences': 'Explorează experiențe',
            'View points of interest': 'Vezi puncte de interes',
            'Please describe your desired trip.': 'Vă rog să descrieți călătoria dorită.',
            'An unexpected error occurred.': 'A apărut o eroare neașteptată.',
            'Could not process the request. Please try again.': 'Nu am putut procesa cererea. Vă rog să încercați din nou.'
        };
        return translations[key] || key;
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        if (!description.trim() || description.length < 10) {
            setError(t('Please describe your desired trip.'));
            return;
        }

        setIsLoading(true);
        setError(null);
        setRecommendations(null);
        setExperiences([]);
        setPointsOfInterest([]);
        setSearchTerms(null);

        try {
            router.post('/trip-planner', {
                description: description.trim()
            }, {
                preserveScroll: true,
                onSuccess: (page) => {
                    const response = page.props.tripPlannerResult as any;
                    if (response?.success) {
                        setRecommendations(response.recommendations || '');
                        setExperiences(response.experiences || []);
                        setPointsOfInterest(response.points_of_interest || []);
                        setSearchTerms(response.search_terms || null);
                    } else {
                        setError(response?.error || t('Could not process the request. Please try again.'));
                    }
                },
                onError: (errors) => {
                    setError(errors.description || t('An unexpected error occurred.'));
                },
                onFinish: () => {
                    setIsLoading(false);
                }
            });
        } catch (err) {
            setError(t('An unexpected error occurred.'));
            setIsLoading(false);
        }
    };

    const exampleDescriptions = [
        t("I want to discover authentic culinary experiences and visit interesting museums in Bucharest."),
        t("I'm planning a cultural trip with art galleries and traditional workshops in Romania."),
        t("I'm looking for adventure activities and local restaurants near Bucharest."),
        t("I want to explore historical points of interest and take part in interactive experiences.")
    ];

    const handleExampleClick = (example: string) => {
        setDescription(example);
        setRecommendations(null);
        setExperiences([]);
        setPointsOfInterest([]);
        setSearchTerms(null);
        setError(null);
    };


    return (
        <AppLayout>
            <Head title={t('Trip Planner')} />

            <div className="min-h-screen">
                <div className="max-w-[1400px] mx-auto px-4 py-8 w-full">
                    {/* Header */}
                    <div className="text-center mb-12">
                        <Badge className="mb-4 bg-gradient-to-r from-blue-600 to-purple-600 text-white">
                            <Star className="h-3 w-3 mr-1" />
                            {t('AI Trip Planner')}
                        </Badge>

                        <h1 className="text-3xl lg:text-4xl font-bold text-foreground mb-4">
                            {t('Plan your perfect trip')}
                        </h1>

                        <p className="text-muted-foreground text-lg max-w-2xl mx-auto leading-relaxed">
                            {t('Describe your dream trip and let AI create personalized recommendations for authentic experiences and fascinating points of interest.')}
                        </p>
                    </div>

                    {/* Trip Planner Form */}
                    <div className="max-w-4xl mx-auto mb-8">
                        <div className="bg-white rounded-xl shadow-lg p-6">
                            <div className="flex items-center gap-2 mb-4">
                                <Navigation className="h-5 w-5 text-blue-600" />
                                <h2 className="text-xl font-semibold">{t('Describe your ideal trip')}</h2>
                            </div>
                            
                            <form onSubmit={handleSubmit} className="space-y-4">
                                <div>
                                    <Label htmlFor="description" className="text-sm font-medium text-gray-700">
                                        {t('Tell us about your travel preferences')}
                                    </Label>
                                    <Textarea
                                        id="description"
                                        placeholder={t('Example: I want to discover authentic culinary experiences and visit interesting museums in Bucharest. I\'m interested in interactive workshops and local restaurants...')}
                                        value={description}
                                        onChange={(e) => setDescription(e.target.value)}
                                        className="mt-2 min-h-[120px] resize-none rounded-lg border-gray-200 focus:border-blue-500 focus:ring-blue-500"
                                        disabled={isLoading}
                                    />
                                    <p className="text-xs text-gray-500 mt-1">
                                        {t('Minimum 10 characters, maximum 1000 characters')}
                                    </p>
                                </div>

                                <Button
                                    type="submit"
                                    disabled={isLoading || description.length < 10}
                                    className="w-full bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white rounded-lg py-3"
                                    size="lg"
                                >
                                    {isLoading ? (
                                        <>
                                            <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                                            {t('Generating recommendations...')}
                                        </>
                                    ) : (
                                        <>
                                            <Search className="h-4 w-4 mr-2" />
                                            {t('Generate trip plan')}
                                        </>
                                    )}
                                </Button>
                            </form>
                        </div>

                        {/* Example Descriptions */}
                        <div className="mt-6">
                            <h3 className="text-lg font-medium mb-3">{t('Ideas for inspiration')}</h3>
                            <div className="grid gap-3 sm:grid-cols-2">
                                {exampleDescriptions.map((example, index) => (
                                    <Button
                                        key={index}
                                        variant="outline"
                                        className="h-auto p-4 text-left justify-start text-sm leading-relaxed hover:bg-blue-50 border-gray-200 rounded-lg"
                                        onClick={() => handleExampleClick(example)}
                                        disabled={isLoading}
                                    >
                                        <div className="text-xs text-gray-500 mr-3 flex-shrink-0">
                                            {index + 1}
                                        </div>
                                        <div className="text-wrap">
                                            {example}
                                        </div>
                                    </Button>
                                ))}
                            </div>
                        </div>
                    </div>

                    {/* Error Display */}
                    {error && (
                        <div className="max-w-4xl mx-auto mb-8 p-4 bg-red-50 border border-red-200 rounded-lg">
                            <div className="text-sm font-medium text-red-700 mb-1">{t('Error')}</div>
                            <p className="text-sm text-red-600">{error}</p>
                        </div>
                    )}

                    {/* Trip Itinerary Display */}
                    {(recommendations || experiences.length > 0 || pointsOfInterest.length > 0) && (
                        <div className="space-y-12">
                            {/* Itinerary Header */}
                            <div className="text-center mb-8">
                                <Badge className="bg-gradient-to-r from-blue-600 to-purple-600 text-white mb-4">
                                    <Navigation className="h-3 w-3 mr-1" />
                                    {t('Your personalized recommendations')}
                                </Badge>
                                <h2 className="text-3xl font-bold text-gray-900 dark:text-gray-100 mb-4">
                                    Itinerariul Tău Perfect
                                </h2>
                                <p className="text-gray-600 dark:text-gray-400 max-w-2xl mx-auto mb-8">
                                    Descoperă experiențe autentice și puncte de interes fascinante pentru călătoria ta
                                </p>
                            </div>

                            {/* Recommendations Content */}
                            {recommendations && (
                                <div className="bg-white rounded-xl shadow-lg p-8 mb-8">
                                    <div className="prose prose-blue max-w-none text-sm leading-relaxed text-left">
                                        <MarkdownRenderer content={recommendations} />
                                    </div>
                                </div>
                            )}

                            {/* Destination Groups */}
                            {(() => {
                                // Group experiences and POIs by location
                                const locationGroups: { [key: string]: { experiences: Experience[], pois: PointOfInterest[] } } = {};

                                // Group experiences
                                experiences.forEach(exp => {
                                    const location = exp.location?.split(',')[0] || 'Other';
                                    if (!locationGroups[location]) locationGroups[location] = { experiences: [], pois: [] };
                                    locationGroups[location].experiences.push(exp);
                                });

                                // Group POIs
                                pointsOfInterest.forEach(poi => {
                                    const location = poi.location?.split(',')[0] || 'Other';
                                    if (!locationGroups[location]) locationGroups[location] = { experiences: [], pois: [] };
                                    locationGroups[location].pois.push(poi);
                                });

                                return Object.entries(locationGroups).map(([location, content], index) => (
                                    <div key={location} className="mb-12">
                                        {/* Location Header */}
                                        <div className="flex items-center gap-4 mb-6">
                                            <div className="flex items-center justify-center w-10 h-10 rounded-full bg-gradient-to-br from-blue-500 to-purple-600 text-white text-lg font-bold">
                                                {index + 1}
                                            </div>
                                            <div>
                                                <h3 className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                                                    {location}
                                                </h3>
                                                <p className="text-gray-600 dark:text-gray-400">
                                                    {content.experiences.length + content.pois.length} activități recomandate
                                                </p>
                                            </div>
                                            <div className="flex gap-2 ml-auto">
                                                {content.experiences.length > 0 && (
                                                    <Badge variant="outline" className="text-green-700 border-green-200">
                                                        <Sparkles className="h-3 w-3 mr-1" />
                                                        {content.experiences.length} experiențe
                                                    </Badge>
                                                )}
                                                {content.pois.length > 0 && (
                                                    <Badge variant="outline" className="text-purple-700 border-purple-200">
                                                        <MapPin className="h-3 w-3 mr-1" />
                                                        {content.pois.length} puncte de interes
                                                    </Badge>
                                                )}
                                            </div>
                                        </div>

                                        {/* Experiences for this location */}
                                        {content.experiences.length > 0 && (
                                            <div className="mb-8">
                                                <h4 className="flex items-center gap-2 text-xl font-semibold text-green-700 dark:text-green-300 mb-4">
                                                    <Sparkles className="h-5 w-5" />
                                                    Experiențe Autentice
                                                </h4>
                                                <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
                                                    {content.experiences.map((experience) => (
                                                        <Link key={experience.id} href={`/experiences/${experience.id}`} className="block group">
                                                            <div className="transform transition-all duration-300 group-hover:scale-105 group-hover:shadow-xl">
                                                                <ExperienceCard
                                                                    image={experience.image_url || ''}
                                                                    title={experience.content.substring(0, 50) + (experience.content.length > 50 ? '...' : '')}
                                                                    description={experience.content}
                                                                    category="Experience"
                                                                    rating={experience.engagement_rate}
                                                                    price="Free"
                                                                    duration=""
                                                                    location={experience.location}
                                                                />
                                                            </div>
                                                        </Link>
                                                    ))}
                                                </div>
                                            </div>
                                        )}

                                        {/* POIs for this location */}
                                        {content.pois.length > 0 && (
                                            <div>
                                                <h4 className="flex items-center gap-2 text-xl font-semibold text-purple-700 dark:text-purple-300 mb-4">
                                                    <MapPin className="h-5 w-5" />
                                                    Puncte de Interes
                                                </h4>
                                                <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
                                                    {content.pois.map((poi) => (
                                                        <Link key={poi.id} href={`/points-of-interest/${poi.id}`} className="block group">
                                                            <div className="transform transition-all duration-300 group-hover:scale-105 group-hover:shadow-xl">
                                                                <PointOfInterestCard
                                                                    image={poi.image_url || ''}
                                                                    title={poi.name}
                                                                    description={poi.description}
                                                                    category={poi.category?.name || 'General'}
                                                                    rating={parseFloat(poi.engagement || '0')}
                                                                    priceRange=""
                                                                    openingHours=""
                                                                    location={poi.location}
                                                                    features={[]}
                                                                />
                                                            </div>
                                                        </Link>
                                                    ))}
                                                </div>
                                            </div>
                                        )}
                                    </div>
                                ));
                            })()}

                            {/* Action Buttons */}
                            <div className="text-center py-8 border-t border-gray-200">
                                <h3 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-2">
                                    Gata să îți începi aventura?
                                </h3>
                                <p className="text-gray-600 dark:text-gray-400 mb-6">
                                    Explorează mai multe experiențe și puncte de interes sau creează un plan nou
                                </p>
                                <div className="flex flex-col sm:flex-row gap-4 justify-center">
                                    <Button variant="outline" className="px-6" asChild>
                                        <Link href="/experiences">
                                            <Sparkles className="h-4 w-4 mr-2" />
                                            {t('Explore experiences')}
                                        </Link>
                                    </Button>
                                    <Button variant="outline" className="px-6" asChild>
                                        <Link href="/points-of-interest">
                                            <MapPin className="h-4 w-4 mr-2" />
                                            {t('View points of interest')}
                                        </Link>
                                    </Button>
                                    <Button
                                        className="px-6 bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700"
                                        onClick={() => {
                                            setDescription('');
                                            setRecommendations(null);
                                            setExperiences([]);
                                            setPointsOfInterest([]);
                                            setSearchTerms(null);
                                            setError(null);
                                        }}
                                    >
                                        <Navigation className="h-4 w-4 mr-2" />
                                        Planificare nouă
                                    </Button>
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </AppLayout>
    );
};

export default TripPlanner;