"use client";

import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { 
  Calendar, 
  Star, 
  MapPin, 
  ShieldCheck,
  Briefcase,
  Heart,
  MessageCircle,
  Globe,
  GraduationCap
} from "lucide-react";
import { Button } from "@/components/ui/button";
import Link from "next/link";
import Image from "next/image";
import { getCountryFlag } from "@/lib/constants";

interface User {
  id: string;
  name: string | null;
  image: string | null;
  bio: string | null;
  role: "GUIDE" | "EXPLORER";
  university: string | null;
  semester: string | null;
  countryOfOrigin: string | null;
  createdAt: string;
}

interface GuideStats {
  toursCreated: number;
  totalReviews: number;
  avgRating: number;
  activeBookings: number;
  tours?: Array<{
    id: string;
    title: string;
    slug: string;
    description: string;
    city: string;
    priceCents: number | null;
    durationMin: number | null;
    maxGuests: number | null;
    avgRating: number | null;
    reviewCount: number;
    images: Array<{ url: string }>;
  }>;
  reviews?: Array<{
    id: string;
    rating: number;
    comment: string | null;
    createdAt: string;
    user: {
      name: string | null;
      image: string | null;
    };
    tour: {
      title: string;
    };
  }>;
}

interface ExplorerStats {
  bookingsCompleted: number;
  reviewsWritten: number;
}

interface PublicProfileContentProps {
  user: User;
  stats: GuideStats | ExplorerStats;
}

export default function PublicProfileContent({ user, stats }: PublicProfileContentProps) {

  const initials = user.name?.charAt(0).toUpperCase() || "U";

  const formatPrice = (priceInCents: number | null) => {
    if (!priceInCents) return "Free";
    return `CHF ${(priceInCents / 100).toFixed(0)}`;
  };

  const formatDuration = (minutes: number | null) => {
    if (!minutes) return "N/A";
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    if (mins === 0) return `${hours}h`;
    return `${hours}h ${mins}m`;
  };

  const isGuide = user.role === "GUIDE";
  const guideStats = stats as GuideStats;
  const explorerStats = stats as ExplorerStats;

  return (
    <div className="min-h-screen bg-white">
      {/* Hero Section - Airbnb Style */}
      <div className="border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
          <div className="flex flex-col md:flex-row gap-8 items-start">
            {/* Avatar Section */}
            <div className="relative">
              <Avatar className="h-32 w-32 ring-4 ring-white shadow-xl">
                <AvatarImage src={user.image || undefined} alt={user.name || "User"} />
                <AvatarFallback className="text-4xl bg-linear-to-br from-blue-500 to-blue-600 text-white">
                  {initials}
                </AvatarFallback>
              </Avatar>
              {/* Superhost Badge */}
              {isGuide && guideStats.totalReviews >= 5 && guideStats.avgRating >= 4.5 && (
                <div className="absolute -bottom-2 -right-2 bg-pink-500 text-white rounded-full p-2 shadow-lg">
                  <ShieldCheck className="h-5 w-5" />
                </div>
              )}
            </div>

            {/* Profile Info */}
            <div className="flex-1">
              <div className="mb-6">
                <h1 className="text-4xl font-bold mb-2">{user.name || "Anonymous"}</h1>
                {isGuide && guideStats.totalReviews >= 5 && guideStats.avgRating >= 4.5 && (
                  <Badge variant="default" className="bg-pink-500 hover:bg-pink-600 mb-3">
                    <ShieldCheck className="h-3 w-3 mr-1" />
                    Superhost
                  </Badge>
                )}
              </div>

              {/* Stats Row */}
              <div className="flex flex-wrap gap-6 mb-6">
                <div className="flex items-center gap-2">
                  <Star className="h-5 w-5" />
                  <span className="font-semibold text-lg">
                    {isGuide ? (
                      <>
                        {guideStats.totalReviews} Review{guideStats.totalReviews !== 1 ? "s" : ""}
                      </>
                    ) : (
                      <>
                        {explorerStats.reviewsWritten} Review{explorerStats.reviewsWritten !== 1 ? "s" : ""}
                      </>
                    )}
                  </span>
                </div>

                <div className="flex items-center gap-2">
                  <Star className="h-5 w-5 fill-yellow-400 text-yellow-400" />
                  <span className="font-semibold text-lg">
                    {isGuide ? guideStats.avgRating.toFixed(2) : "N/A"}
                  </span>
                  <span className="text-muted-foreground">Rating</span>
                </div>

                <div className="flex items-center gap-2">
                  <Calendar className="h-5 w-5" />
                  <span className="font-semibold text-lg">
                    {isGuide ? guideStats.toursCreated : explorerStats.bookingsCompleted}
                  </span>
                  <span className="text-muted-foreground">
                    {isGuide ? "Years hosting" : "Tours taken"}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        <div className="grid lg:grid-cols-3 gap-12">
          {/* Left Column - About Section */}
          <div className="lg:col-span-2 space-y-12">
            {/* About Section */}
            <div>
              <h2 className="text-2xl font-bold mb-6">
                About {user.name || "this user"}
              </h2>
              
              <div className="space-y-6">
                {/* Bio */}
                {user.bio && (
                  <p className="text-base text-gray-600 leading-relaxed whitespace-pre-wrap">
                    {user.bio}
                  </p>
                )}

                {/* Quick Facts */}
                <div className="grid sm:grid-cols-2 gap-4 py-6 border-t border-b">
                  {user.university && user.semester && (
                    <div className="flex items-start gap-3">
                      <GraduationCap className="h-5 w-5 mt-0.5 text-gray-600" />
                      <div>
                        <p className="font-medium">{user.university}</p>
                        <p className="text-sm text-gray-500">{user.semester}</p>
                      </div>
                    </div>
                  )}
                  {user.countryOfOrigin && (
                    <div className="flex items-start gap-3">
                      <Globe className="h-5 w-5 mt-0.5 text-gray-600" />
                      <div>
                        <p className="font-medium">
                          From {getCountryFlag(user.countryOfOrigin)} {user.countryOfOrigin}
                        </p>
                      </div>
                    </div>
                  )}
                  {isGuide && (
                    <>
                      <div className="flex items-start gap-3">
                        <Briefcase className="h-5 w-5 mt-0.5 text-gray-600" />
                        <div>
                          <p className="font-medium">My work: Tour Guide</p>
                        </div>
                      </div>
                    </>
                  )}
                </div>

                {/* Verified Badge */}
                <div className="flex items-center gap-2 text-sm">
                  <ShieldCheck className="h-5 w-5 text-blue-600" />
                  <span className="font-medium underline">Identity verified</span>
                </div>
              </div>
            </div>

            {/* Reviews Section */}
            {isGuide && guideStats.reviews && guideStats.reviews.length > 0 && (
              <div>
                <h2 className="text-2xl font-bold mb-6">
                  {user.name}&apos;s reviews
                </h2>
                
                <div className="space-y-8">
                  {guideStats.reviews.slice(0, 6).map((review) => (
                    <div key={review.id} className="space-y-3">
                      {/* Review Header */}
                      <div className="flex items-start gap-4">
                        <Avatar className="h-12 w-12">
                          <AvatarImage src={review.user.image || undefined} />
                          <AvatarFallback className="bg-gray-100">
                            {review.user.name?.charAt(0).toUpperCase() || "U"}
                          </AvatarFallback>
                        </Avatar>
                        <div className="flex-1">
                          <p className="font-semibold">{review.user.name || "Anonymous"}</p>
                          <p className="text-sm text-gray-500">
                            {new Date(review.createdAt).toLocaleDateString("en-US", {
                              month: "long",
                              year: "numeric",
                            })}
                          </p>
                        </div>
                      </div>

                      {/* Rating */}
                      <div className="flex items-center gap-1">
                        {[...Array(5)].map((_, i) => (
                          <Star
                            key={i}
                            className={`h-4 w-4 ${
                              i < review.rating
                                ? "fill-black text-black"
                                : "fill-gray-200 text-gray-200"
                            }`}
                          />
                        ))}
                      </div>

                      {/* Comment */}
                      {review.comment && (
                        <p className="text-gray-600 leading-relaxed">
                          {review.comment}
                        </p>
                      )}
                    </div>
                  ))}
                </div>

                {guideStats.totalReviews > 6 && (
                  <Button variant="outline" className="mt-6" asChild>
                    <Link href="#reviews">
                      Show more reviews
                    </Link>
                  </Button>
                )}
              </div>
            )}
          </div>

          {/* Right Column - Additional Info */}
          <div className="space-y-8">
            {isGuide && (
              <Card className="border-2">
                <CardContent className="p-6 space-y-4">
                  <h3 className="text-lg font-semibold">Confirmed information</h3>
                  
                  <div className="space-y-3 text-sm">
                    <div className="flex items-center gap-2">
                      <ShieldCheck className="h-4 w-4" />
                      <span>Identity</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <MessageCircle className="h-4 w-4" />
                      <span>Email address</span>
                    </div>
                  </div>
                </CardContent>
              </Card>
            )}
          </div>
        </div>

        {/* Tours/Listings Section */}
        {isGuide && guideStats.tours && guideStats.tours.length > 0 && (
          <div className="mt-16">
            <h2 className="text-2xl font-bold mb-8">
              {user.name}&apos;s listings
            </h2>
            
            <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
              {guideStats.tours.map((tour) => (
                <Link
                  key={tour.id}
                  href={`/tours/${tour.slug}`}
                  className="group"
                >
                  <div className="space-y-3">
                    {/* Tour Image */}
                    <div className="relative aspect-square rounded-xl overflow-hidden bg-gray-200">
                      {tour.images[0] ? (
                        <Image
                          src={tour.images[0].url}
                          alt={tour.title}
                          fill
                          className="object-cover transition-transform group-hover:scale-105"
                        />
                      ) : (
                        <div className="flex items-center justify-center h-full bg-linear-to-br from-blue-100 to-blue-200">
                          <MapPin className="h-12 w-12 text-blue-400" />
                        </div>
                      )}
                    </div>

                    {/* Tour Info */}
                    <div className="space-y-1">
                      <div className="flex items-center justify-between">
                        <h3 className="font-semibold text-gray-900 line-clamp-1">
                          {tour.city}
                        </h3>
                        {tour.avgRating && (
                          <div className="flex items-center gap-1">
                            <Star className="h-3.5 w-3.5 fill-black text-black" />
                            <span className="text-sm font-medium">
                              {tour.avgRating.toFixed(2)}
                            </span>
                          </div>
                        )}
                      </div>
                      
                      <p className="text-sm text-gray-500 line-clamp-1">
                        {tour.title}
                      </p>
                      
                      <p className="text-sm text-gray-500">
                        {formatDuration(tour.durationMin)}
                      </p>
                      
                      <p className="font-semibold">
                        <span className="underline">{formatPrice(tour.priceCents)}</span> per person
                      </p>
                    </div>
                  </div>
                </Link>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
