import type { GetServerSideProps, NextPage } from 'next';
import Head from 'next/head';
import { useEffect, useState } from 'react';
import toast from 'react-hot-toast';
import Breadcrumbs, { breadcrumbsJsonLd } from '../components/Breadcrumbs';
import { SITE_URL } from '../lib/seo';
import { fetchFromApi } from '../lib/serverFetch';

interface Review {
  id: number;
  author: string;
  rating: number;
  date: string;
  text: string;
  title?: string;
}

interface ReviewsPageProps {
  initialReviews: Review[];
}

const Reviews: NextPage<ReviewsPageProps> = ({ initialReviews }) => {
  const [reviews, setReviews] = useState<Review[]>(initialReviews);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showForm, setShowForm] = useState(false);
  
  const [formData, setFormData] = useState({
    author_name: '',
    author_email: '',
    rating: 5,
    title: '',
    text: ''
  });

  useEffect(() => {
    setReviews(initialReviews);
  }, [initialReviews]);

  const handleSubmitReview = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);

    try {
      const response = await fetch('/api/reviews', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData)
      });

      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.error);
      }

      toast.success('Recenze byla odeslána. Díky za váš názor!');
      setFormData({ author_name: '', author_email: '', rating: 5, title: '', text: '' });
      setShowForm(false);
      
      // Reload reviews (only approved ones show)
      const updatedResponse = await fetch('/api/reviews');
      const updatedData = await updatedResponse.json();
      setReviews(updatedData);
    } catch (error) {
      toast.error(error instanceof Error ? error.message : 'Chyba při odesílání recenze');
    } finally {
      setIsSubmitting(false);
    }
  };

  const averageRating = reviews.length > 0 
    ? (reviews.reduce((sum, review) => sum + review.rating, 0) / reviews.length).toFixed(1)
    : '0';
  
  const totalReviews = reviews.length;

  const renderStars = (rating: number) => {
    return (
      <div className="flex gap-1">
        {[...Array(5)].map((_, i) => (
          <svg
            key={i}
            className={`w-4 h-4 sm:w-5 sm:h-5 ${
              i < rating ? 'text-luxury-gold' : 'text-luxury-gold/30'
            }`}
            fill="currentColor"
            viewBox="0 0 20 20"
          >
            <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
          </svg>
        ))}
      </div>
    );
  };

  return (
    <>
      <Head>
        <title>Hodnocení obchodu | Recenze zákazníků | Vystříkejto.cz</title>
        <meta name="description" content="Přečtěte si recenze zákazníků na celé parfémy z Vystříkejto.cz. Originální vůně a rychlé doručení." />
        <link rel="canonical" href="https://vystrikejto.cz/reviews" />
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{
            __html: JSON.stringify([
              breadcrumbsJsonLd([
                { name: 'Domů', href: '/' },
                { name: 'Hodnocení obchodu' },
              ]),
              {
                '@context': 'https://schema.org',
                '@type': 'OnlineStore',
                name: 'Vystříkejto.cz',
                url: SITE_URL,
                aggregateRating: totalReviews > 0 ? {
                  '@type': 'AggregateRating',
                  ratingValue: averageRating,
                  reviewCount: totalReviews,
                  bestRating: 5,
                  worstRating: 1,
                } : undefined,
                review: reviews.slice(0, 20).map((review) => ({
                  '@type': 'Review',
                  author: { '@type': 'Person', name: review.author },
                  datePublished: review.date,
                  reviewBody: review.text,
                  name: review.title,
                  reviewRating: {
                    '@type': 'Rating',
                    ratingValue: review.rating,
                    bestRating: 5,
                    worstRating: 1,
                  },
                })),
              },
            ]),
          }}
        />
      </Head>
      <div className="min-h-screen bg-luxury-dark py-16 sm:py-12 md:py-20">
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="pt-20 md:pt-32 mb-6">
          <Breadcrumbs items={[{ name: 'Domů', href: '/' }, { name: 'Hodnocení obchodu' }]} />
        </div>
        {/* Header */}
        <div className="mb-12 md:mb-16 text-center">
          <h1 className="text-4xl sm:text-3xl md:text-5xl font-aptos font-bold uppercase text-luxury-gold mb-4">
            Hodnocení Obchodu
          </h1>
        </div>

        {/* Rating Summary */}
        <div className="mb-12 md:mb-16 bg-gradient-to-b from-luxury-dark to-luxury-dark border border-luxury-gold/20 rounded-lg p-6 md:p-8">
          <div className="flex flex-col md:flex-row items-center gap-8">
            <div className="text-center">
              <div className="text-6xl md:text-7xl font-aptos font-bold text-luxury-gold mb-2">
                {averageRating}
              </div>
              <div className="mb-3">
                {renderStars(Math.round(parseFloat(averageRating)))}
              </div>
              <p className="text-luxury-light/60 text-lg">
                na základě {totalReviews} recenzí
              </p>
            </div>

            <div className="flex-grow">
              <h2 className="text-2xl font-aptos font-bold text-luxury-gold mb-4">
                Jsme hrdí na naši službu
              </h2>
              <p className="text-luxury-light/80 text-lg leading-relaxed">
                Naši zákazníci si cení kvality našich produktů, rychlosti doručení a profesionálního přístupu. Vaše zpětná vazba nám pomáhá neustále se zlepšovat.
              </p>
            </div>
          </div>
        </div>

        {/* Reviews List */}
        <div>
          <div className="flex justify-between items-center mb-6">
            <h2 className="text-2xl md:text-3xl font-aptos font-bold text-luxury-gold">
              Recenze Zákazníků
            </h2>
            <button
              onClick={() => setShowForm(!showForm)}
              className="px-4 py-2 bg-luxury-gold text-luxury-dark font-bold rounded-lg hover:bg-yellow-300 transition-all"
            >
              {showForm ? 'Zrušit' : 'Přidat Recenzi'}
            </button>
          </div>

          {/* Review Form */}
          {showForm && (
            <form
              onSubmit={handleSubmitReview}
              className="bg-luxury-gold/5 border border-luxury-gold/30 rounded-lg p-6 mb-8 space-y-4"
            >
              <div>
                <label className="block text-luxury-gold font-bold mb-2">Jméno</label>
                <input
                  type="text"
                  required
                  value={formData.author_name}
                  onChange={(e) => setFormData({...formData, author_name: e.target.value})}
                  className="w-full px-4 py-2 bg-luxury-dark border border-luxury-gold/30 rounded-lg text-luxury-light focus:outline-none focus:border-luxury-gold"
                  placeholder="Vaše jméno"
                />
              </div>

              <div>
                <label className="block text-luxury-gold font-bold mb-2">E-mail</label>
                <input
                  type="email"
                  required
                  value={formData.author_email}
                  onChange={(e) => setFormData({...formData, author_email: e.target.value})}
                  className="w-full px-4 py-2 bg-luxury-dark border border-luxury-gold/30 rounded-lg text-luxury-light focus:outline-none focus:border-luxury-gold"
                  placeholder="Váš e-mail"
                />
              </div>

              <div>
                <label className="block text-luxury-gold font-bold mb-2">Nadpis (volitelně)</label>
                <input
                  type="text"
                  value={formData.title}
                  onChange={(e) => setFormData({...formData, title: e.target.value})}
                  className="w-full px-4 py-2 bg-luxury-dark border border-luxury-gold/30 rounded-lg text-luxury-light focus:outline-none focus:border-luxury-gold"
                  placeholder="Nadpis recenze"
                />
              </div>

              <div>
                <label className="block text-luxury-gold font-bold mb-2">Hodnocení</label>
                <div className="flex gap-2">
                  {[1, 2, 3, 4, 5].map((rating) => (
                    <button
                      key={rating}
                      type="button"
                      onClick={() => setFormData({...formData, rating})}
                      className={`px-4 py-2 rounded-lg font-bold transition-all ${
                        formData.rating === rating
                          ? 'bg-luxury-gold text-luxury-dark'
                          : 'bg-luxury-dark border border-luxury-gold/30 text-luxury-gold hover:border-luxury-gold'
                      }`}
                    >
                      {rating}★
                    </button>
                  ))}
                </div>
              </div>

              <div>
                <label className="block text-luxury-gold font-bold mb-2">Recenze (min. 10 znaků)</label>
                <textarea
                  required
                  minLength={10}
                  value={formData.text}
                  onChange={(e) => setFormData({...formData, text: e.target.value})}
                  className="w-full px-4 py-2 bg-luxury-dark border border-luxury-gold/30 rounded-lg text-luxury-light focus:outline-none focus:border-luxury-gold h-32 resize-none"
                  placeholder="Vaše recenze..."
                />
              </div>

              <button
                type="submit"
                disabled={isSubmitting}
                className="w-full px-4 py-3 bg-luxury-gold text-luxury-dark font-bold rounded-lg hover:bg-yellow-300 transition-all disabled:opacity-50"
              >
                {isSubmitting ? 'Odesílání...' : 'Odeslat Recenzi'}
              </button>
            </form>
          )}

          {/* Reviews Display - Grid Layout */}
          {reviews.length === 0 ? (
            <div className="text-center py-8">
              <p className="text-luxury-light/60 text-lg">Zatím nejsou žádné schválené recenze.</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {reviews.map((review) => (
                <div
                  key={review.id}
                  className="bg-gradient-to-b from-luxury-dark to-luxury-dark border border-luxury-gold/20 rounded-lg p-4 md:p-6 hover:border-luxury-gold/50 transition-all duration-300 flex flex-col"
                >
                  <div className="mb-4">
                    <h3 className="text-lg font-aptos font-bold text-luxury-light mb-2">
                      {review.author}
                    </h3>
                    {review.title && (
                      <p className="text-luxury-gold font-semibold mb-2 text-sm">"{review.title}"</p>
                    )}
                    <div className="mb-2">
                      {renderStars(review.rating)}
                    </div>
                  </div>

                  <p className="text-luxury-light/80 text-base leading-relaxed flex-grow mb-4">
                    {review.text}
                  </p>

                  <p className="text-luxury-light/60 text-sm">
                    {review.date}
                  </p>
                </div>
              ))}
            </div>
          )}
        </div>

      </div>
    </div>
    </>
  );
};

export const getServerSideProps: GetServerSideProps<ReviewsPageProps> = async ({ req }) => {
  const reviews = await fetchFromApi<Review[]>(req, '/api/reviews');
  return {
    props: {
      initialReviews: reviews || [],
    },
  };
};

export default Reviews;
