'use client';

import React, { useState, useEffect, Suspense } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { Header } from '../components/Header';
import { Footer } from '../components/Footer';
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;
}

function ReportsContent() {
  const [reports, setReports] = useState<Report[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isVisible, setIsVisible] = useState(false);

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

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

  const fetchReports = async () => {
    try {
      setLoading(true);
      setError(null);

      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;
      }

      setReports(reportsData);
    } catch (err: any) {
      console.error('Error fetching reports:', err);
      setError(err?.message || 'Failed to load reports');
    } 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) {
      const firstMedia = report.media[0];
      window.open(firstMedia.url, '_blank');
    }
  };

  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 FeaturedReport = ({ report }: { report: Report }) => {
    const imageUrl = resolveImage(report);
    const hasDocuments = Boolean(report.media && report.media.length > 0);
    const isLocalhost = imageUrl.includes('localhost') || imageUrl.includes('127.0.0.1');

    return (
      <article className="group mb-12 overflow-hidden rounded-3xl border border-secondary-200 bg-white shadow-sm transition-shadow duration-300 hover:shadow-xl lg:mb-16">
        <div className="grid grid-cols-1 lg:grid-cols-2">
          <Link href={`/reports/${report.slug}`} className="relative min-h-[16rem] overflow-hidden sm:min-h-[22rem] lg:min-h-[28rem]">
            <Image
              src={imageUrl}
              alt={report.name}
              fill
              className="object-cover transition-transform duration-700 group-hover:scale-105"
              sizes="(max-width: 1024px) 100vw, 50vw"
              unoptimized={isLocalhost}
            />
            <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 sm:py-12 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/${report.slug}`}>
              <h2 className="mt-4 text-2xl font-black leading-tight text-neutral-900 transition-colors group-hover:text-primary-600 sm:text-3xl md:text-4xl">
                {report.name}
              </h2>
            </Link>

            {report.description && (
              <p className="mt-4 line-clamp-3 text-base leading-relaxed text-neutral-600">
                {report.description}
              </p>
            )}

            <div className="mt-6 flex flex-wrap items-center gap-4 text-sm text-neutral-500">
              {report.published_date && <span>{formatDate(report.published_date)}</span>}
              {report.views_count > 0 && <span>{report.views_count} views</span>}
              {hasDocuments && (
                <span>
                  {report.media?.length} document{report.media && report.media.length > 1 ? 's' : ''}
                </span>
              )}
            </div>

            <div className="mt-8 flex flex-wrap gap-3">
              <Link
                href={`/reports/${report.slug}`}
                className="inline-flex items-center gap-2 rounded-lg bg-navy-800 px-5 py-2.5 text-sm font-bold text-white transition-colors hover:bg-navy-700"
              >
                Read report
                <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>
              {hasDocuments && (
                <button
                  type="button"
                  onClick={(e) => handleDownload(e, report)}
                  className="inline-flex items-center gap-2 rounded-lg border border-secondary-300 px-5 py-2.5 text-sm font-bold text-neutral-800 transition-colors hover:border-primary-500"
                >
                  Download
                </button>
              )}
            </div>
          </div>
        </div>
      </article>
    );
  };

  const ReportCard = ({ report }: { report: Report }) => {
    const imageUrl = resolveImage(report);
    const hasDocuments = Boolean(report.media && report.media.length > 0);
    const isLocalhost = imageUrl.includes('localhost') || imageUrl.includes('127.0.0.1');

    return (
      <div className="group bg-white rounded-xl shadow-md hover:shadow-xl transition-all duration-500 transform hover:-translate-y-2 border border-neutral-100 h-full flex flex-col overflow-hidden">
        <Link href={`/reports/${report.slug}`} className="relative h-52 w-full overflow-hidden bg-neutral-100 flex-shrink-0">
          <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}
          />
        </Link>

        <div className="p-6 flex-1 flex flex-col">
          <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>

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

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

          {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>
          )}

          <div className="flex items-center gap-3 pt-4 border-t border-neutral-100 mt-auto">
            <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"
            >
              <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
            </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>
        </div>
      </div>
    );
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-white">
        <Header />
        <div className="min-h-[80vh] flex items-center justify-center px-4">
          <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>
        <Footer />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-white">
      <Header />

      {/* Hero Section */}
      <section className="relative overflow-hidden border-b border-secondary-200 bg-white pt-28 pb-12 sm:pt-32 sm:pb-16">
        <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 transition-all duration-700 sm:px-6 lg:px-8 ${
            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>

          <h1 className="mt-5 text-4xl font-black leading-tight text-neutral-900 sm:text-5xl md:text-6xl">
            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>
          </h1>

          <p className="mt-6 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>
      </section>

      {/* Reports Grid */}
      <section className={`py-12 md:py-16 transition-all duration-1000 ${isVisible ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'}`}>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          {reports.length > 0 ? (
            <>
              <FeaturedReport report={reports[0]} />
              <div className="grid grid-cols-1 gap-6 md:grid-cols-2 md:gap-8 lg:grid-cols-3">
                {reports.slice(1).map((report, index) => (
                  <ReportCard key={report.id || index} report={report} />
                ))}
              </div>
            </>
          ) : (
            <div className="text-center py-24 bg-neutral-50 rounded-2xl border border-neutral-200">
              <div className="inline-flex items-center justify-center w-20 h-20 rounded-full bg-primary-100 mb-6">
                <svg className="w-10 h-10 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>
              <h3 className="text-2xl font-bold text-neutral-900 mb-3">No reports yet</h3>
              <p className="text-neutral-600 text-lg">Check back soon for our latest reports and publications.</p>
            </div>
          )}
        </div>
      </section>

      {/* Error Message */}
      {error && (
        <section className="py-20">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="bg-red-50 border-2 border-red-200 rounded-2xl p-8 text-center">
              <p className="text-xl text-red-600 mb-4 font-semibold">Error: {error}</p>
              <button
                onClick={fetchReports}
                className="inline-flex items-center px-6 py-3 border border-transparent text-sm font-medium rounded-xl shadow-sm text-neutral-900 bg-primary-500 hover:bg-primary-400 transition-colors"
              >
                Retry
              </button>
            </div>
          </div>
        </section>
      )}

      <Footer />
    </div>
  );
}

export default function ReportsPage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen bg-white">
        <Header />
        <div className="min-h-[80vh] flex items-center justify-center px-4">
          <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...</p>
          </div>
        </div>
        <Footer />
      </div>
    }>
      <ReportsContent />
    </Suspense>
  );
}

