import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '@/contexts/AuthContext';
import { useQuery } from '@tanstack/react-query';
import { tripsApi, tripDaysApi } from '@/db/api';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';

export default function Journal() {
  const navigate = useNavigate();
  const { user } = useAuth();
  const [selectedTripId, setSelectedTripId] = useState<string | null>(null);
  const [selectedDay, setSelectedDay] = useState<number>(1);

  const { data: trips, isLoading: tripsLoading } = useQuery({
    queryKey: ['user-trips', user?.id],
    queryFn: () => tripsApi.getUserTrips(user!.id),
    enabled: !!user
  });

  useEffect(() => {
    if (trips && trips.length > 0 && !selectedTripId) {
      const latestTrip = [...trips].sort((a, b) => 
        new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
      )[0];
      setSelectedTripId(latestTrip.id);
    }
  }, [trips, selectedTripId]);

  const { data: tripDays, isLoading: daysLoading } = useQuery({
    queryKey: ['trip-days', selectedTripId],
    queryFn: () => tripDaysApi.getByTripId(selectedTripId!),
    enabled: !!selectedTripId
  });

  if (!user) {
    return (
      <div className="container mx-auto px-4 py-8">
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <p className="text-lg text-muted-foreground mb-4">
              Günlüğünüzü görmek için giriş yapın
            </p>
            <Button onClick={() => navigate('/login')}>
              Giriş Yap
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  if (!tripsLoading && (!trips || trips.length === 0)) {
    return (
      <div className="container mx-auto px-4 py-8">
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <p className="text-lg text-muted-foreground mb-4">
              Henüz seyahat planınız yok
            </p>
            <Button onClick={() => navigate('/create-trip')}>
              Seyahat Oluştur
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  if (tripsLoading || (selectedTripId && daysLoading)) {
    return (
      <div className="container mx-auto px-4 py-8">
        <Skeleton className="h-12 w-[300px] mb-6" />
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
          <Skeleton className="h-[600px]" />
          <div className="lg:col-span-3">
            <Skeleton className="h-[600px]" />
          </div>
        </div>
      </div>
    );
  }

  const days = tripDays?.map(day => ({
    id: day.id,
    day: day.day_number,
    date: new Date(day.date).toLocaleDateString('tr-TR', { 
      day: 'numeric', 
      month: 'long' 
    }),
    notes: day.notes || 'Henüz not eklenmedi'
  })) || [];

  const currentDayData = days.find(d => d.day === selectedDay);

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="mb-6">
        <Select value={selectedTripId || ''} onValueChange={setSelectedTripId}>
          <SelectTrigger className="w-[300px]">
            <SelectValue placeholder="Seyahat seçin" />
          </SelectTrigger>
          <SelectContent>
            {trips?.map(trip => (
              <SelectItem key={trip.id} value={trip.id}>
                {trip.name} - {new Date(trip.start_date).toLocaleDateString('tr-TR')}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
        <Card>
          <CardContent className="p-4">
            <h3 className="font-semibold mb-4">Günler</h3>
            <div className="space-y-2">
              {days.map(day => (
                <button
                  key={day.id}
                  onClick={() => setSelectedDay(day.day)}
                  className={`w-full text-left p-3 rounded-lg transition-colors ${
                    selectedDay === day.day
                      ? 'bg-primary text-primary-foreground'
                      : 'hover:bg-muted'
                  }`}
                >
                  <div className="font-medium">Gün {day.day}</div>
                  <div className="text-sm opacity-80">{day.date}</div>
                </button>
              ))}
              {days.length === 0 && <p className="text-sm text-muted-foreground">Gün bulunamadı</p>}
            </div>
          </CardContent>
        </Card>

        <div className="lg:col-span-3">
          <Tabs defaultValue="journal">
            <TabsList>
              <TabsTrigger value="journal">Günlük</TabsTrigger>
              <TabsTrigger value="gallery">Galeri</TabsTrigger>
            </TabsList>

            <TabsContent value="journal">
              <Card>
                <CardContent className="p-6">
                  <div className="flex items-center justify-between mb-4">
                    <h2 className="text-2xl font-bold">
                      Gün {selectedDay}
                    </h2>
                    {currentDayData && <Badge>{currentDayData.date}</Badge>}
                  </div>
                  <div className="prose max-w-none dark:prose-invert">
                    <p>{currentDayData?.notes}</p>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="gallery">
              <Card>
                <CardContent className="p-6">
                  <div className="text-center py-12">
                    <p className="text-muted-foreground">Fotoğraf Galerisi yakında</p>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>
          </Tabs>
        </div>
      </div>
    </div>
  );
}
