
'use client';

import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import Image from 'next/image';
import {
  ArrowUpRight,
  Heart,
  MessageCircle,
  Milestone,
  Clock,
  ClipboardList,
  Bed,
  Camera,
} from 'lucide-react';
import Link from 'next/link';
import { trails, gear, events } from '@/lib/data';
import { PlaceHolderImages } from '@/lib/placeholder-images';
import { Badge } from '@/components/ui/badge';
import { isAfter } from 'date-fns';

export default function HomePage() {
  const heroTrail = PlaceHolderImages.find((p) => p.id === 'hero-trail');
  const featuredTrail = trails[1];
  const newGear = gear[0];
  const recentPhotos = trails.slice(0, 4);

  const upcomingEvent =
    events.find((event) => {
      try {
        const eventDate = new Date(
          event.date.replace(/(\d+)(st|nd|rd|th)/, '$1')
        );
        return isAfter(eventDate, new Date());
      } catch (e) {
        return false;
      }
    }) ||
    events.sort(
      (a, b) =>
        new Date(b.date.replace(/(\d+)(st|nd|rd|th)/, '$1')).getTime() -
        new Date(a.date.replace(/(\d+)(st|nd|rd|th)/, '$1')).getTime()
    )[0];

  const isEventExpired = (dateString: string) => {
    try {
      const eventDate = new Date(dateString.replace(/(\d+)(st|nd|rd|th)/, '$1'));
      return !isAfter(eventDate, new Date());
    } catch (e) {
      return false;
    }
  };

  return (
    <div className="flex flex-col gap-8">
      <section className="relative h-64 w-full rounded-lg overflow-hidden">
        {heroTrail?.imageUrl && (
          <Image
            src={heroTrail.imageUrl}
            alt={heroTrail.description}
            fill
            className="object-cover"
            priority
            data-ai-hint={heroTrail.imageHint}
          />
        )}
        <div className="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent" />
        <div className="absolute bottom-0 left-0 p-6 md:p-8">
          <h1 className="text-3xl md:text-4xl font-bold text-white">
            Find Your Next Ride
          </h1>
          <p className="mt-2 max-w-lg text-lg text-gray-200">
            Explore epic roads, connect with riders, and gear up.
          </p>
        </div>
      </section>

      {upcomingEvent && (
        <section>
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-2xl font-bold tracking-tight">
              {isEventExpired(upcomingEvent.date)
                ? 'Recent Event'
                : 'Upcoming Event'}
            </h2>
            {isEventExpired(upcomingEvent.date) && (
              <Badge variant="destructive">Expired</Badge>
            )}
          </div>
          <Card className="bg-card">
            <CardHeader>
              <CardTitle>{upcomingEvent.destination}</CardTitle>
              <CardDescription>{upcomingEvent.date}</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-2 md:grid-cols-3 gap-4 text-sm">
                <div className="flex items-center gap-2">
                  <Milestone className="text-primary" />
                  <span>
                    <span className="font-semibold">Distance:</span>{' '}
                    {upcomingEvent.distance}
                  </span>
                </div>
                <div className="flex items-center gap-2">
                  <Clock className="text-primary" />
                  <span>
                    <span className="font-semibold">Duration:</span>{' '}
                    {upcomingEvent.duration}
                  </span>
                </div>
                {upcomingEvent.daycation && (
                  <div className="flex items-center gap-2">
                    <Bed className="text-primary" />
                    <span>
                      <span className="font-semibold">Daycation:</span>{' '}
                      {upcomingEvent.daycation}
                    </span>
                  </div>
                )}
              </div>
              <div>
                <h4 className="font-semibold flex items-center gap-2 mb-2">
                  <ClipboardList className="text-primary" />
                  Activities
                </h4>
                <p className="text-muted-foreground">
                  {upcomingEvent.activities}
                </p>
              </div>
            </CardContent>
          </Card>
        </section>
      )}

      <section className="grid grid-cols-1 gap-6 lg:grid-cols-3">
        <div className="lg:col-span-2">
          <h2 className="text-2xl font-bold tracking-tight mb-4">
            Featured Route
          </h2>
          <Card className="overflow-hidden">
            {featuredTrail?.imageUrl && (
              <Image
                src={featuredTrail.imageUrl}
                alt={featuredTrail.name}
                width={800}
                height={400}
                className="w-full object-cover h-60"
                data-ai-hint={featuredTrail.imageHint}
              />
            )}
            <CardHeader>
              <div className="flex items-start justify-between">
                <div>
                  <CardTitle>{featuredTrail.name}</CardTitle>
                  <CardDescription>
                    {featuredTrail.location}
                  </CardDescription>
                </div>
                <Badge
                  variant={
                    featuredTrail.difficulty === 'Advanced'
                      ? 'destructive'
                      : featuredTrail.difficulty === 'Intermediate'
                      ? 'secondary'
                      : 'default'
                  }
                  className="bg-accent text-accent-foreground"
                >
                  {featuredTrail.difficulty}
                </Badge>
              </div>
            </CardHeader>
            <CardContent>
              <p className="text-muted-foreground line-clamp-2">
                {featuredTrail.description}
              </p>
              <div className="mt-4 flex items-center justify-between text-sm text-muted-foreground">
                <div className="flex gap-4">
                  <span className="flex items-center gap-1">
                    <Heart className="w-4 h-4" /> {featuredTrail.likes}
                  </span>
                  <span className="flex items-center gap-1">
                    <MessageCircle className="w-4 h-4" />{' '}
                    {featuredTrail.comments}
                  </span>
                </div>
                <Button variant="ghost" size="sm" asChild>
                  <Link href="#">
                    View Route <ArrowUpRight className="w-4 h-4 ml-1" />
                  </Link>
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>

        <div className="flex flex-col gap-6">
          <div>
            <h2 className="text-2xl font-bold tracking-tight mb-4">
              New Gear
            </h2>
            <Card className="overflow-hidden">
              {newGear?.images?.[0]?.url && (
                <Image
                  src={newGear.images[0].url}
                  alt={newGear.name}
                  width={400}
                  height={400}
                  className="w-full object-cover h-48"
                  data-ai-hint={newGear.images[0].hint}
                />
              )}
              <CardHeader>
                <CardTitle className="text-lg line-clamp-1">
                  {newGear.name}
                </CardTitle>
                <CardDescription>${newGear.price}</CardDescription>
              </CardHeader>
              <CardContent>
                <Button
                  className="w-full bg-accent text-accent-foreground hover:bg-accent/90"
                  asChild
                >
                  <Link href={`/marketplace/${newGear.id}`}>
                    Check it out
                  </Link>
                </Button>
              </CardContent>
            </Card>
          </div>
        </div>
      </section>

      <section>
        <h2 className="text-2xl font-bold tracking-tight mb-4 flex items-center gap-2">
          <Camera /> Recent Rides & Photos
        </h2>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {recentPhotos.map((photo) => (
            <Card key={photo.id} className="overflow-hidden group">
              <Link href="#" className="block relative aspect-square">
                {photo.imageUrl && (
                  <Image
                    src={photo.imageUrl}
                    alt={photo.name}
                    fill
                    className="object-cover group-hover:scale-105 transition-transform duration-300"
                    data-ai-hint={photo.imageHint}
                  />
                )}
                <div className="absolute inset-0 bg-gradient-to-t from-black/50 to-transparent" />
                <p className="absolute bottom-2 left-2 text-white text-sm font-semibold">
                  {photo.name}
                </p>
              </Link>
            </Card>
          ))}
        </div>
      </section>
    </div>
  );
}
