'use client';

import { useState, useEffect } from 'react';
import Image from 'next/image';
import { testimonialsService, Testimonial } from '@/services/testimonials.service';

function StarRating({ rating }: { rating: number }) {
  return (
    <div className="flex items-center gap-1">
      {Array.from({ length: rating }).map((_, i) => (
        <Image
          key={i}
          src="/assets/icons/star-filled-icon.svg"
          alt=""
          width={16}
          height={16}
        />
      ))}
    </div>
  );
}

function TestimonialCard({ testimonial }: { testimonial: Testimonial }) {
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

    if (diffDays === 0) return 'Today';
    if (diffDays === 1) return '1 day ago';
    if (diffDays < 30) return `${diffDays} days ago`;
    if (diffDays < 60) return '1 month ago';
    if (diffDays < 365) return `${Math.floor(diffDays / 30)} months ago`;
    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
  };

  return (
    <div className="bg-white rounded-[7px] p-4">
      <StarRating rating={testimonial.rating} />
      <p className="font-serif text-[14px] text-black mt-3 leading-[22px]">
        {testimonial.text}
      </p>
      <p className="mt-3 text-[14px] text-[#00293D]">
        <span className="font-fractul font-bold">{testimonial.authorName} ,</span>
        <span className="font-fractul font-light"> {testimonial.authorRole} · {formatDate(testimonial.createdAt)}</span>
      </p>
    </div>
  );
}

export function TestimonialsForm() {
  const [copied, setCopied] = useState(false);
  const [testimonialLink, setTestimonialLink] = useState('');
  const [testimonials, setTestimonials] = useState<Testimonial[]>([]);
  const [sortOrder, setSortOrder] = useState<'latest' | 'oldest'>('latest');
  const [loading, setLoading] = useState(true);
  const [generating, setGenerating] = useState(false);

  const fetchTestimonials = async (sort: 'latest' | 'oldest') => {
    try {
      setLoading(true);
      const data = await testimonialsService.getMyTestimonials(sort);
      setTestimonials(data);
    } catch (err) {
      console.error('Failed to fetch testimonials:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchTestimonials(sortOrder);
  }, [sortOrder]);

  const handleGenerateLink = async () => {
    try {
      setGenerating(true);
      const { token } = await testimonialsService.generateLink();
      const baseUrl = window.location.origin;
      setTestimonialLink(`${baseUrl}/testimonials/${token}`);
    } catch (err) {
      console.error('Failed to generate link:', err);
    } finally {
      setGenerating(false);
    }
  };

  const handleCopyLink = async () => {
    if (!testimonialLink) return;
    try {
      await navigator.clipboard.writeText(testimonialLink);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      // Fallback for older browsers
    }
  };

  return (
    <>
      {/* Page Title */}
      <div className="mb-6">
        <h1 className="font-fractul font-bold text-[20px] text-[#00293D] mb-2">
          Add Testimonials
        </h1>
        <p className="font-fractul font-medium text-[14px] text-[#00293D]">
          What people are saying about you
        </p>
      </div>

      {/* Create Testimonials Section */}
      <div className="border border-[#00293D]/10 rounded-[7px] p-6 mb-6">
        <h2 className="font-fractul font-bold text-[20px] text-[#00293D] mb-4">
          Create Testimonials
        </h2>

        <div className="flex flex-col sm:flex-row gap-3">
          {/* Generate Link Button */}
          <button
            onClick={handleGenerateLink}
            disabled={generating}
            className="bg-[#e58625] text-white font-fractul font-bold text-[14px] px-8 py-3 rounded-[15px] hover:bg-[#d47920] transition-colors whitespace-nowrap disabled:opacity-50"
          >
            {generating ? 'Generating...' : 'Generate Link'}
          </button>

          {/* Link Input with Copy */}
          <div className="flex-1 flex items-center border border-[#00293D]/10 rounded-[15px] overflow-hidden">
            <span className="flex-1 font-fractul font-light text-[14px] text-black px-4 py-3 truncate">
              {testimonialLink || 'Click "Generate Link" to create a shareable link'}
            </span>
            {testimonialLink && (
              <>
                <div className="h-[46px] w-px bg-[#00293D]/10" />
                <button
                  onClick={handleCopyLink}
                  className="flex items-center gap-1.5 px-4 py-3 hover:bg-gray-50 transition-colors"
                >
                  <Image
                    src="/assets/icons/copy-icon.svg"
                    alt="Copy"
                    width={16}
                    height={16}
                  />
                  <span className="font-serif font-light text-[14px] text-black">
                    {copied ? 'Copied!' : 'Copy'}
                  </span>
                </button>
              </>
            )}
          </div>
        </div>
      </div>

      {/* Testimonials */}
      {loading ? (
        <div className="flex items-center justify-center py-12">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#E58625]"></div>
        </div>
      ) : testimonials.length === 0 ? (
        <div className="text-center py-12 bg-[#d9d9d9]/25 rounded-[7px]">
          <p className="font-fractul font-medium text-[16px] text-[#00293D]/60">
            No testimonials yet
          </p>
          <p className="font-fractul font-light text-[14px] text-[#00293D]/40 mt-2">
            Generate a link and share it to collect testimonials
          </p>
        </div>
      ) : (
        <div className="bg-[#d9d9d9]/25 rounded-[7px] p-5">
          <button
            onClick={() => setSortOrder(sortOrder === 'latest' ? 'oldest' : 'latest')}
            className="flex items-center gap-1 mb-4 hover:opacity-70 transition-opacity"
          >
            <span className="font-fractul font-medium text-[14px] text-black">
              Sort By : {sortOrder === 'latest' ? 'Latest' : 'Oldest'}
            </span>
            <Image
              src="/assets/icons/sort-arrow-down-icon.svg"
              alt=""
              width={14}
              height={14}
              className={sortOrder === 'oldest' ? 'rotate-180' : ''}
            />
          </button>
          <div className="space-y-4 max-h-[600px] overflow-y-auto pr-1 custom-scrollbar">
            {testimonials.map((testimonial) => (
              <TestimonialCard key={testimonial.id} testimonial={testimonial} />
            ))}
          </div>
        </div>
      )}

      {/* Custom scrollbar styles */}
      <style jsx>{`
        .custom-scrollbar::-webkit-scrollbar {
          width: 5px;
        }
        .custom-scrollbar::-webkit-scrollbar-track {
          background: #d9d9d9;
          border-radius: 2px;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb {
          background: rgba(0, 41, 61, 0.25);
          border-radius: 2px;
        }
      `}</style>
    </>
  );
}
