'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import api from '@/lib/api';

interface Report {
  id: number;
  name: string;
  slug: string;
  description: string | null;
  status: string;
  published_date: string | null;
  published_date_human: string | null;
  order: number;
  authors: Array<{ name: string }> | null;
  keywords: string[] | null;
  meta_title: string | null;
  meta_description: string | null;
  views_count: number;
  downloads_count: number;
  thumbnail: string | null;
  media: Array<{
    id: number;
    name: string;
    file_name: string;
    mime_type: string;
    size: number;
    human_readable_size: string;
    url: string;
    created_at: string;
  }> | null;
  created_at: string;
  updated_at: string;
}

/**
 * Latest Reports Section
 * Displays recent reports with view and download functionality
 */
export const LatestReports: React.FC = () => {
  const [reports, setReports] = useState<Report[]>([]);
  const [loading, setLoading] = useState(true);
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    fetchReports();
  }, []);

  useEffect(() => {
    if (!loading) {
      setTimeout(() => setIsVisible(true), 100);
    }
  }, [loading]);

  const fetchReports = async () => {
    try {
      setLoading(true);
      const response: any = await api.getReports({
        status: 'published',
        paginate: false,
        order_by: 'order',
        order_direction: 'asc',
      });

      let reportsData: any[] = [];
      if (Array.isArray(response)) {
        reportsData = response;
      } else if (response && typeof response === 'object' && 'data' in response && Array.isArray(response.data)) {
        reportsData = response.data;
      }

      // Get latest 6 reports
      setReports(reportsData.slice(0, 6));
    } catch (err: any) {
      console.error('Error fetching reports:', err);
    } finally {
      setLoading(false);
    }
  };

  const formatDate = (dateString: string | null) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
  };

  const handleDownload = (e: React.MouseEvent, report: Report) => {
    e.preventDefault();
    e.stopPropagation();
    
    if (report.media && report.media.length > 0) {
      // Download the first document
      const firstMedia = report.media[0];
      window.open(firstMedia.url, '_blank');
      
      // Track download (you can add API call here to increment downloads_count)
    }
  };

  if (loading) {
    return (
      <section className="py-20 md:py-32 bg-white">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center">
            <div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600 mb-4"></div>
            <p className="text-neutral-600">Loading reports...</p>
          </div>
        </div>
      </section>
    );
  }

  if (reports.length === 0) {
    return null;
  }

  const resolveImage = (report: Report) => {
    if (!report.thumbnail) return '/images/IMG_9722.JPG';
    return report.thumbnail.startsWith('http')
      ? report.thumbnail
      : `${process.env.NEXT_PUBLIC_API_URL?.replace('/api/v1', '') || 'http://localhost:8000'}${report.thumbnail}`;
  };

  const featured = reports[0];
  const moreReports = reports.slice(1);

  return (
    <section className="relative overflow-hidden bg-white py-20 md:py-28">
      <div className="pointer-events-none absolute -left-24 top-10 h-64 w-64 rounded-full bg-primary-500/10 blur-3xl" />
      <div className="pointer-events-none absolute -right-16 bottom-0 h-56 w-56 rounded-full bg-navy-800/5 blur-3xl" />

      <div className="relative mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
        <div
          className={`mb-12 transition-all duration-700 md:mb-16 ${
            isVisible ? 'translate-y-0 opacity-100' : 'translate-y-6 opacity-0'
          }`}
        >
          <span className="inline-flex items-center gap-2 rounded-full border border-primary-500/30 bg-primary-500/10 px-4 py-1.5 text-xs font-bold uppercase tracking-widest text-primary-700">
            <span className="h-1.5 w-1.5 rounded-full bg-primary-500" />
            Publications
          </span>
          <h2 className="mt-5 text-3xl font-black leading-tight text-neutral-900 sm:text-4xl md:text-5xl">
            Our latest{' '}
            <span className="relative inline-block text-primary-600">
              reports
              <svg
                className="absolute -bottom-2 left-0 w-full text-primary-400"
                viewBox="0 0 160 12"
                preserveAspectRatio="none"
                aria-hidden
              >
                <path d="M2 9C40 2 120 2 158 9" stroke="currentColor" strokeWidth="4" strokeLinecap="round" fill="none" />
              </svg>
            </span>
          </h2>
          <p className="mt-5 max-w-2xl text-lg leading-relaxed text-neutral-600">
            Program updates, impact assessments, and organizational publications from SSEOA&apos;s
            work across Afghanistan.
          </p>
        </div>

        <div
          className={`transition-all duration-700 delay-150 ${
            isVisible ? 'translate-y-0 opacity-100' : 'translate-y-6 opacity-0'
          }`}
        >
          {featured && (
            <article className="group mb-12 overflow-hidden rounded-3xl border border-secondary-200 bg-white shadow-sm transition-shadow duration-300 hover:shadow-xl">
              <div className="grid grid-cols-1 lg:grid-cols-2">
                <Link
                  href={`/reports/${featured.slug}`}
                  className="relative min-h-[16rem] overflow-hidden sm:min-h-[20rem] lg:min-h-[26rem]"
                >
                  <Image
                    src={resolveImage(featured)}
                    alt={featured.name}
                    fill
                    className="object-cover transition-transform duration-700 group-hover:scale-105"
                    sizes="(max-width: 1024px) 100vw, 50vw"
                    unoptimized={
                      resolveImage(featured).includes('localhost') ||
                      resolveImage(featured).includes('127.0.0.1')
                    }
                  />
                  <div className="absolute bottom-0 left-0 right-0 h-1.5 bg-primary-500" />
                </Link>
                <div className="flex flex-col justify-center px-6 py-8 sm:px-10 lg:px-12">
                  <span className="w-fit rounded-full bg-primary-500 px-3 py-1 text-xs font-bold uppercase tracking-wide text-neutral-900">
                    Latest report
                  </span>
                  <Link href={`/reports/${featured.slug}`}>
                    <h3 className="mt-4 text-2xl font-black leading-tight text-neutral-900 transition-colors group-hover:text-primary-600 sm:text-3xl">
                      {featured.name}
                    </h3>
                  </Link>
                  {featured.description && (
                    <p className="mt-4 line-clamp-3 text-base leading-relaxed text-neutral-600">
                      {featured.description}
                    </p>
                  )}
                  <div className="mt-6 flex flex-wrap items-center gap-4 text-sm text-neutral-500">
                    {featured.published_date && <span>{formatDate(featured.published_date)}</span>}
                    {featured.views_count > 0 && <span>{featured.views_count} views</span>}
                  </div>
                  <Link
                    href={`/reports/${featured.slug}`}
                    className="mt-8 inline-flex items-center gap-2 text-sm font-bold text-navy-800"
                  >
                    Read report
                    <svg
                      className="h-4 w-4 transition-transform duration-300 group-hover:translate-x-1"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                      aria-hidden
                    >
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 8l4 4m0 0l-4 4m4-4H3" />
                    </svg>
                  </Link>
                </div>
              </div>
            </article>
          )}

          <div className="grid grid-cols-1 gap-6 md:grid-cols-2 md:gap-8 lg:grid-cols-3">
            {moreReports.map((report) => {
              const imageUrl = resolveImage(report);
              const hasDocuments = report.media && report.media.length > 0;
              // Use unoptimized for localhost URLs to avoid Next.js image optimization issues
              const isLocalhost = imageUrl.includes('localhost') || imageUrl.includes('127.0.0.1');

              return (
                <div
                  key={report.id}
                  className="group bg-white rounded-xl shadow-md hover:shadow-2xl transition-all duration-500 transform hover:-translate-y-2 border border-neutral-100 overflow-hidden flex flex-col"
                >
                  {/* Thumbnail */}
                  <Link href={`/reports/${report.slug}`} className="relative h-48 w-full overflow-hidden bg-neutral-100 flex-shrink-0">
                    {imageUrl ? (
                      <Image
                        src={imageUrl}
                        alt={report.name}
                        fill
                        className="object-cover scale-100 group-hover:scale-110 transition-transform duration-700"
                        sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                        unoptimized={isLocalhost}
                      />
                    ) : (
                      <div className="w-full h-full bg-gradient-to-br from-primary-100 to-primary-200 flex items-center justify-center">
                        <svg className="w-16 h-16 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                        </svg>
                      </div>
                    )}
                    <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
                  </Link>

                  {/* Content */}
                  <div className="p-6 flex-1 flex flex-col">
                    {/* Meta Info */}
                    <div className="flex items-center gap-3 text-xs text-neutral-500 mb-3 font-medium">
                      {report.published_date && (
                        <span className="flex items-center gap-1.5">
                          <svg className="w-3.5 h-3.5" 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>
                          {formatDate(report.published_date)}
                        </span>
                      )}
                      {report.views_count > 0 && (
                        <span className="flex items-center gap-1.5">
                          <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                          </svg>
                          {report.views_count}
                        </span>
                      )}
                    </div>

                    {/* Title */}
                    <Link href={`/reports/${report.slug}`}>
                      <h3 className="text-xl font-bold text-neutral-900 mb-3 group-hover:text-primary-600 transition-colors line-clamp-2 leading-tight flex-1">
                        {report.name}
                      </h3>
                    </Link>

                    {/* Description */}
                    {report.description && (
                      <p className="text-neutral-600 leading-relaxed mb-4 line-clamp-2 text-sm flex-1">
                        {report.description}
                      </p>
                    )}

                    {/* Authors */}
                    {report.authors && report.authors.length > 0 && (
                      <div className="flex items-center gap-2 mb-4 text-xs text-neutral-500">
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} 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>
                        <span className="line-clamp-1">
                          {report.authors.map(a => a.name).join(', ')}
                        </span>
                      </div>
                    )}

                    {/* Actions */}
                    <div className="flex items-center gap-3 pt-4 border-t border-neutral-100">
                      <Link
                        href={`/reports/${report.slug}`}
                        className="flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 bg-primary-500 text-neutral-900 rounded-lg font-medium text-sm hover:bg-primary-700 transition-colors group"
                      >
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                        </svg>
                        View Report
                      </Link>
                      {hasDocuments && (
                        <button
                          onClick={(e) => handleDownload(e, report)}
                          className="inline-flex items-center justify-center gap-2 px-4 py-2.5 bg-neutral-100 text-neutral-700 rounded-lg font-medium text-sm hover:bg-neutral-200 transition-colors"
                          title={`Download ${report.media?.[0]?.file_name || 'document'}`}
                        >
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                          </svg>
                          Download
                        </button>
                      )}
                    </div>

                    {/* Document Count */}
                    {hasDocuments && report.media && report.media.length > 1 && (
                      <div className="mt-2 text-xs text-neutral-500 text-center">
                        {report.media.length} document{report.media.length > 1 ? 's' : ''} available
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>

          {/* View All Link */}
          <div className="mt-12 text-center">
            <Link
              href="/reports"
              className="inline-flex items-center gap-2 rounded-lg bg-navy-800 px-6 py-3 text-sm font-bold text-white transition-colors hover:bg-navy-700"
            >
              View all reports
              <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden>
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 8l4 4m0 0l-4 4m4-4H3" />
              </svg>
            </Link>
          </div>
        </div>
      </div>
    </section>
  );
};

