import type { NextPage } from 'next';
import Head from 'next/head';
import { useSession } from 'next-auth/react';
import { useAuth } from '../context/AuthContext';
import Link from 'next/link';
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
import toast from 'react-hot-toast';

interface ProfileData {
  user: {
    id: string;
    firstName: string;
    lastName: string;
    email: string;
    isActive: boolean;
    memberSince: string;
    profilePicture?: string;
  };
  statistics: {
    totalOrders: number;
    lastOrder: {
      id: number;
      orderNumber: string;
      date: string;
      total: number;
    } | null;
    daysSinceLastOrder: number | null;
    newsletterSubscribed: boolean;
  };
}

const Profile: NextPage = () => {
  const { status } = useSession();
  const { user, logout } = useAuth();
  const router = useRouter();
  const [profileData, setProfileData] = useState<ProfileData | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    if (status === 'unauthenticated') {
      router.push('/login');
    }
  }, [status, router]);

  useEffect(() => {
    const fetchProfileData = async () => {
      try {
        const response = await fetch('/api/user/profile');
        if (response.ok) {
          const data = await response.json();
          setProfileData(data);
        } else {
          toast.error('Chyba při načítání profilu');
        }
      } catch (error) {
        toast.error('Chyba při připojení');
      } finally {
        setIsLoading(false);
      }
    };

    if (status === 'authenticated' && user?.id) {
      fetchProfileData();
    }
  }, [status, user?.id]);

  const handleLogout = async () => {
    toast.success('Úspěšně odhlášeno!', {
      duration: 3000,
    });
    await logout();
    setTimeout(() => {
      router.push('/');
    }, 100);
  };

  if (status === 'loading') {
    return (
      <div className="min-h-screen flex items-center justify-center pt-48 pb-8">
        <div className="text-luxury-light">Načítání...</div>
      </div>
    );
  }

  if (status === 'unauthenticated' || !user) {
    return null;
  }

  return (
    <>
      <Head>
        <title>Můj účet | Vystříkejto.cz</title>
        <meta name="robots" content="noindex,nofollow,noarchive" />
      </Head>
      <div className="min-h-screen w-full bg-luxury-dark pt-48 pb-16">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Top Banner with Avatar */}
        <div className="mb-12">
          <div className="bg-gradient-to-r from-luxury-gold/10 to-luxury-gold/5 border border-luxury-gold/30 rounded-xl p-8 md:p-12">
            <div className="flex flex-col md:flex-row items-start md:items-center gap-8">
              {/* Avatar */}
              <div className="flex-shrink-0">
                {profileData?.user.profilePicture ? (
                  <img
                    src={profileData.user.profilePicture}
                    alt={`${profileData.user.firstName} ${profileData.user.lastName}`}
                    className="w-24 h-24 md:w-32 md:h-32 rounded-full object-cover border-2 border-luxury-gold/40"
                  />
                ) : (
                  <div className="w-24 h-24 md:w-32 md:h-32 bg-gradient-to-br from-luxury-gold/40 to-luxury-gold/10 border-2 border-luxury-gold/40 rounded-full flex items-center justify-center">
                    <svg className="w-12 h-12 md:w-16 md:h-16 text-luxury-gold" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                    </svg>
                  </div>
                )}
              </div>

              {/* User Info */}
              <div className="flex-1">
                <p className="text-luxury-light/50 text-sm font-semibold uppercase tracking-widest mb-2">Přihlášený účet</p>
                <h1 className="text-4xl md:text-5xl font-aptos font-black text-luxury-light mb-2">
                  {user.firstName} {user.lastName}
                </h1>
                <p className="text-luxury-light/70 flex items-center gap-2 mb-4">
                  <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                    <path d="M2.003 5.884L10 9.882l7.997-3.998A2 2 0 0016 4H4a2 2 0 00-1.997 1.884z" />
                    <path d="M18 8.118l-8 4-8-4V14a2 2 0 002 2h12a2 2 0 002-2V8.118z" />
                  </svg>
                  {user.email}
                </p>
              </div>

            </div>
          </div>
        </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-12">
          {/* Total Orders */}
          <div className="bg-luxury-dark/40 border border-luxury-gold/20 rounded-lg p-6 hover:bg-luxury-dark/60 transition-colors">
            <div className="flex items-start justify-between">
              <div className="flex-1">
                <p className="text-luxury-light/50 text-xs font-semibold uppercase tracking-wider mb-2">Objednávky</p>
                <p className="text-3xl font-aptos font-black text-luxury-light">
                  {isLoading ? '-' : profileData?.statistics.totalOrders || 0}
                </p>
              </div>
              <div className="flex-shrink-0 p-3 bg-luxury-gold/10 rounded-lg">
                <svg className="w-6 h-6 text-luxury-gold" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z" />
                </svg>
              </div>
            </div>
          </div>

          {/* Last Purchase */}
          <div className="bg-luxury-dark/40 border border-luxury-gold/20 rounded-lg p-6 hover:bg-luxury-dark/60 transition-colors">
            <div className="flex items-start justify-between">
              <div className="flex-1">
                <p className="text-luxury-light/50 text-xs font-semibold uppercase tracking-wider mb-2">Poslední nákup</p>
                <p className="text-3xl font-aptos font-black text-luxury-light">
                  {isLoading ? '-' : profileData?.statistics.daysSinceLastOrder !== null
                    ? `${profileData?.statistics.daysSinceLastOrder} ${profileData?.statistics.daysSinceLastOrder === 1 ? 'den zpět' : profileData?.statistics.daysSinceLastOrder === 2 || profileData?.statistics.daysSinceLastOrder === 3 || profileData?.statistics.daysSinceLastOrder === 4 ? 'dny zpět' : 'dní zpět'}`
                    : 'Ještě ne'}
                </p>
              </div>
              <div className="flex-shrink-0 p-3 bg-luxury-gold/10 rounded-lg">
                <svg className="w-6 h-6 text-luxury-gold" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              </div>
            </div>
          </div>

          {/* Newsletter Subscription */}
          <div className="bg-luxury-dark/40 border border-luxury-gold/20 rounded-lg p-6 hover:bg-luxury-dark/60 transition-colors">
            <div className="flex items-start justify-between">
              <div className="flex-1">
                <p className="text-luxury-light/50 text-xs font-semibold uppercase tracking-wider mb-2">Novinky</p>
                <div className="inline-flex items-center gap-2 pt-1">
                  <div className={`w-2.5 h-2.5 rounded-full ${
                    isLoading ? 'bg-gray-500' : profileData?.statistics.newsletterSubscribed ? 'bg-green-500' : 'bg-gray-500'
                  }`}></div>
                  <p className="text-lg font-aptos font-black text-luxury-light">
                    {isLoading ? 'Načítání' : profileData?.statistics.newsletterSubscribed ? 'Přihlášen' : 'Nepřihlášen'}
                  </p>
                </div>
              </div>
              <div className="flex-shrink-0 p-3 bg-luxury-gold/10 rounded-lg">
                <svg className="w-6 h-6 text-luxury-gold" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                </svg>
              </div>
            </div>
          </div>

          {/* Member Since */}
          <div className="bg-luxury-dark/40 border border-luxury-gold/20 rounded-lg p-6 hover:bg-luxury-dark/60 transition-colors">
            <div className="flex items-start justify-between">
              <div className="flex-1">
                <p className="text-luxury-light/50 text-xs font-semibold uppercase tracking-wider mb-2">Člen od</p>
                <p className="text-lg font-aptos font-black text-luxury-light">
                  {isLoading ? '-' : profileData?.user.memberSince || '-'}
                </p>
              </div>
              <div className="flex-shrink-0 p-3 bg-luxury-gold/10 rounded-lg">
                <svg className="w-6 h-6 text-luxury-gold" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                </svg>
              </div>
            </div>
          </div>
        </div>

        {/* Recent Order */}
        <div className="mb-12">
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-lg font-semibold text-luxury-light uppercase tracking-wider flex items-center gap-3">
              <svg className="w-5 h-5 text-luxury-gold" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              Poslední objednávka
            </h2>
            <Link href="/orders">
              <button className="text-luxury-gold hover:text-yellow-300 font-semibold text-sm uppercase tracking-wider transition-colors">
                Všechny objednávky
              </button>
            </Link>
          </div>
          <div className="bg-luxury-dark/40 border border-luxury-gold/20 rounded-lg p-8 hover:bg-luxury-dark/60 hover:border-luxury-gold/40 transition-all cursor-pointer">
            {isLoading ? (
              <p className="text-luxury-light/60">Načítání...</p>
            ) : profileData?.statistics.lastOrder ? (
              <Link href={`/orders/${profileData.statistics.lastOrder.id}`}>
                <div>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
                    {/* Order Number */}
                    <div>
                      <p className="text-luxury-light/50 text-xs font-semibold uppercase tracking-wider mb-3">Číslo objednávky</p>
                      <p className="text-2xl font-aptos font-black text-luxury-light">{profileData.statistics.lastOrder.orderNumber}</p>
                    </div>
                    {/* Order Date */}
                    <div>
                      <p className="text-luxury-light/50 text-xs font-semibold uppercase tracking-wider mb-3">Datum</p>
                      <p className="text-lg font-semibold text-luxury-light">{profileData.statistics.lastOrder.date}</p>
                    </div>
                    {/* Order Total */}
                    <div>
                      <p className="text-luxury-light/50 text-xs font-semibold uppercase tracking-wider mb-3">Částka</p>
                      <div className="flex flex-wrap items-center gap-6">
                        <p className="text-2xl font-aptos font-black text-luxury-gold whitespace-nowrap">{Number(profileData.statistics.lastOrder.total).toFixed(2)} Kč</p>
                        <div className="flex items-center text-luxury-gold hover:text-yellow-300 font-semibold text-sm uppercase tracking-wider gap-2 transition-colors border border-luxury-gold/30 px-4 py-2 rounded-lg bg-luxury-gold/5 hover:bg-luxury-gold/10 whitespace-nowrap">
                          Zobrazit objednávku
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                          </svg>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </Link>
            ) : (
              <p className="text-luxury-light/60">Zatím jste nezadali žádnou objednávku</p>
            )}
          </div>
        </div>
        {/* Action Buttons */}
        <div className="flex flex-col sm:flex-row gap-4">
          <Link href="/">
            <button className="flex-1 px-8 py-4 bg-luxury-gold hover:bg-yellow-300 text-luxury-dark font-aptos font-bold rounded-lg transition-all duration-300 text-base uppercase tracking-widest">
              Pokračovat v nákupu
            </button>
          </Link>
          <button
            onClick={handleLogout}
            className="flex-1 px-8 py-4 border-2 border-luxury-light/30 hover:border-luxury-light/50 text-luxury-light hover:text-luxury-light font-bold rounded-lg transition-all duration-300 text-base uppercase tracking-widest"
          >
            Odhlásit se
          </button>
        </div>
      </div>
    </div>
    </>
  );
};

export default Profile;
