'use client';

import React, { useState, useEffect, Suspense } from 'react';
import { useParams } from 'next/navigation';
import Image from 'next/image';
import Link from 'next/link';
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 ReportContent() {
  const params = useParams();
  const slug = params?.slug as string;

  const [report, setReport] = useState<Report | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    if (slug) {
      fetchReport();
    }
  }, [slug]);

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

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

      const response: any = await api.getReport(slug);
      
      let reportData: any = null;
      if (response && typeof response === 'object') {
        if ('data' in response) {
          reportData = response.data;
        } else {
          reportData = response;
        }
      }

      setReport(reportData);
    } catch (err: any) {
      console.error('Error fetching report:', err);
      setError(err?.message || 'Failed to load report');
    } 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 = (mediaUrl: string, fileName: string) => {
    window.open(mediaUrl, '_blank');
  };

  const getFileIcon = (mimeType: string) => {
    if (mimeType.includes('pdf')) {
      return (
        <svg className="w-6 h-6 text-red-600" fill="currentColor" viewBox="0 0 20 20">
          <path fillRule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z" clipRule="evenodd" />
        </svg>
      );
    }
    if (mimeType.includes('word') || mimeType.includes('document')) {
      return (
        <svg className="w-6 h-6 text-blue-600" fill="currentColor" viewBox="0 0 20 20">
          <path fillRule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z" clipRule="evenodd" />
        </svg>
      );
    }
    if (mimeType.includes('excel') || mimeType.includes('spreadsheet')) {
      return (
        <svg className="w-6 h-6 text-green-600" fill="currentColor" viewBox="0 0 20 20">
          <path fillRule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z" clipRule="evenodd" />
        </svg>
      );
    }
    return (
      <svg className="w-6 h-6 text-neutral-600" fill="currentColor" viewBox="0 0 20 20">
        <path fillRule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z" clipRule="evenodd" />
      </svg>
    );
  };

  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 report...</p>
          </div>
        </div>
        <Footer />
      </div>
    );
  }

  if (error || !report) {
    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 max-w-md">
            <div className="inline-flex items-center justify-center w-20 h-20 rounded-full bg-red-100 mb-6">
              <svg className="w-10 h-10 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
            <h2 className="text-2xl font-bold text-neutral-900 mb-3">Report Not Found</h2>
            <p className="text-neutral-600 mb-6">{error || 'The report you are looking for does not exist.'}</p>
            <Link
              href="/reports"
              className="inline-flex items-center gap-2 px-6 py-3 bg-primary-500 text-neutral-900 rounded-lg font-medium hover:bg-primary-700 transition-colors"
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
              </svg>
              Back to Reports
            </Link>
          </div>
        </div>
        <Footer />
      </div>
    );
  }

  // Ensure thumbnail URL is valid - check if it's a full URL or relative path
  const imageUrl = report.thumbnail 
    ? (report.thumbnail.startsWith('http') ? report.thumbnail : `${process.env.NEXT_PUBLIC_API_URL?.replace('/api/v1', '') || 'http://localhost:8000'}${report.thumbnail}`)
    : '/images/default-avatar.svg';
  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 className="min-h-screen bg-white">
      <Header />

      {/* Hero Section with Image */}
      <section className="relative bg-white pt-32 pb-12 md:pt-40 md:pb-16">
        <div className={`max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 transition-all duration-1000 ${isVisible ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'}`}>
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-12">
            {/* Main Content */}
            <div className="lg:col-span-2">
              {/* Breadcrumb */}
              <nav className="flex mb-6 text-sm text-neutral-600">
                <Link href="/" className="hover:text-primary-600 transition-colors">Home</Link>
                <span className="mx-2">/</span>
                <Link href="/reports" className="hover:text-primary-600 transition-colors">Reports</Link>
                <span className="mx-2">/</span>
                <span className="text-neutral-900">{report.name}</span>
              </nav>

              {/* Title */}
              <h1 className="text-4xl md:text-5xl lg:text-6xl font-bold text-primary-500 mb-6 leading-tight">
                {report.name}
              </h1>

              {/* Meta Information */}
              <div className="flex flex-wrap items-center gap-4 mb-6 text-sm text-neutral-600">
                {report.published_date && (
                  <span className="flex items-center gap-2">
                    <svg className="w-4 h-4" 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-2">
                    <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>
                    {report.views_count} views
                  </span>
                )}
                {report.downloads_count > 0 && (
                  <span className="flex items-center gap-2">
                    <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>
                    {report.downloads_count} downloads
                  </span>
                )}
              </div>

              {/* Authors */}
              {report.authors && report.authors.length > 0 && (
                <div className="mb-6">
                  <div className="flex items-center gap-2 text-sm text-neutral-600 mb-2">
                    <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="font-medium">Authors:</span>
                  </div>
                  <div className="flex flex-wrap gap-2">
                    {report.authors.map((author, index) => (
                      <span key={index} className="px-3 py-1 bg-primary-50 text-primary-700 rounded-full text-sm font-medium">
                        {author.name}
                      </span>
                    ))}
                  </div>
                </div>
              )}

              {/* Keywords */}
              {report.keywords && report.keywords.length > 0 && (
                <div className="mb-6">
                  <div className="flex flex-wrap gap-2">
                    {report.keywords.map((keyword, index) => (
                      <span key={index} className="px-3 py-1 bg-neutral-100 text-neutral-700 rounded-full text-sm">
                        #{keyword}
                      </span>
                    ))}
                  </div>
                </div>
              )}

              {/* Description */}
              {report.description && (
                <div className="prose prose-lg max-w-none mb-8">
                  <p className="text-lg text-neutral-700 leading-relaxed">
                    {report.description}
                  </p>
                </div>
              )}

              {/* Download Documents Section */}
              {hasDocuments && report.media && (
                <div className="bg-neutral-50 rounded-xl p-6 border border-neutral-200 mb-8">
                  <h3 className="text-xl font-bold text-neutral-900 mb-4 flex items-center gap-2">
                    <svg className="w-5 h-5 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>
                    Documents ({report.media.length})
                  </h3>
                  <div className="space-y-3">
                    {report.media.map((media) => (
                      <button
                        key={media.id}
                        onClick={() => handleDownload(media.url, media.file_name)}
                        className="w-full flex items-center justify-between p-4 bg-white rounded-lg border border-neutral-200 hover:border-primary-500 hover:shadow-md transition-all duration-300 group"
                      >
                        <div className="flex items-center gap-4">
                          {getFileIcon(media.mime_type)}
                          <div className="text-left">
                            <div className="font-medium text-neutral-900 group-hover:text-primary-600 transition-colors">
                              {media.name || media.file_name}
                            </div>
                            <div className="text-sm text-neutral-500">
                              {media.human_readable_size} • {media.mime_type.split('/')[1]?.toUpperCase() || 'FILE'}
                            </div>
                          </div>
                        </div>
                        <svg className="w-5 h-5 text-neutral-400 group-hover:text-primary-600 transition-colors" 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>
                      </button>
                    ))}
                  </div>
                </div>
              )}
            </div>

            {/* Sidebar */}
            <div className="lg:col-span-1">
              <div className="sticky top-24 space-y-6">
                {/* Thumbnail */}
                {imageUrl && (
                  <div className="bg-white rounded-xl overflow-hidden shadow-lg border border-neutral-200">
                    <div className="relative h-64 w-full">
                      <Image
                        src={imageUrl}
                        alt={report.name}
                        fill
                        className="object-cover"
                        sizes="(max-width: 1024px) 100vw, 33vw"
                        unoptimized={isLocalhost}
                      />
                    </div>
                  </div>
                )}

                {/* Quick Info */}
                <div className="bg-neutral-50 rounded-xl p-6 border border-neutral-200">
                  <h3 className="text-lg font-bold text-neutral-900 mb-4">Report Information</h3>
                  <div className="space-y-3 text-sm">
                    {report.published_date && (
                      <div>
                        <div className="text-neutral-600 mb-1">Published</div>
                        <div className="font-medium text-neutral-900">{formatDate(report.published_date)}</div>
                      </div>
                    )}
                    <div>
                      <div className="text-neutral-600 mb-1">Views</div>
                      <div className="font-medium text-neutral-900">{report.views_count.toLocaleString()}</div>
                    </div>
                    {report.downloads_count > 0 && (
                      <div>
                        <div className="text-neutral-600 mb-1">Downloads</div>
                        <div className="font-medium text-neutral-900">{report.downloads_count.toLocaleString()}</div>
                      </div>
                    )}
                    {hasDocuments && report.media && (
                      <div>
                        <div className="text-neutral-600 mb-1">Documents</div>
                        <div className="font-medium text-neutral-900">{report.media.length} file{report.media.length > 1 ? 's' : ''}</div>
                      </div>
                    )}
                  </div>
                </div>

                {/* Back to Reports */}
                <Link
                  href="/reports"
                  className="block w-full text-center px-6 py-3 bg-primary-500 text-neutral-900 rounded-lg font-medium hover:bg-primary-700 transition-colors"
                >
                  <svg className="w-5 h-5 inline-block mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                  </svg>
                  Back to Reports
                </Link>
              </div>
            </div>
          </div>
        </div>
      </section>

      <Footer />
    </div>
  );
}

export default function ReportPage() {
  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>
    }>
      <ReportContent />
    </Suspense>
  );
}

