"use client";

import React, { useEffect, useState, Suspense } from 'react';
import Link from 'next/link';
import { ArrowRight, Scale, FileText } from 'lucide-react';
import axios from '@/lib/axios';
import { useTranslations } from 'next-intl';
import { useSearchParams } from 'next/navigation';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';

interface LegalPageItem {
  title: string;
  slug: string;
}

function LegalContent() {
  const t = useTranslations("Legal");
  const searchParams = useSearchParams();
  const pageSlug = searchParams.get('page'); // Changed from 'slug' to 'page' as requested

  const [pages, setPages] = useState<LegalPageItem[]>([]);
  const [activePage, setActivePage] = useState<any>(null);
  const [isLoading, setIsLoading] = useState(true);

  // Fetch List
  useEffect(() => {
    if (pageSlug) return; // Don't fetch list if viewing a page

    const fetchPages = async () => {
      try {
        const { data } = await axios.get(`${process.env.NEXT_PUBLIC_API_URL}/api/public/legal-pages`);
        setPages(data.data as LegalPageItem[]);
      } catch (error) {
        console.error("Failed to fetch legal pages:", error);
      } finally {
        setIsLoading(false);
      }
    };
    fetchPages();
  }, [pageSlug]);

  // Fetch Single Page
  useEffect(() => {
    if (!pageSlug) return;

    const fetchPage = async () => {
      setIsLoading(true);
      try {
         const apiUrl = process.env.NEXT_PUBLIC_API_URL;
         const res = await axios.get(`${apiUrl}/api/public/legal-pages/${pageSlug}`);
         setActivePage(res.data.data);
      } catch (error) {
         console.error(error);
      } finally {
         setIsLoading(false);
      }
    };
    fetchPage();
  }, [pageSlug]);

  // View: Single Page
  if (pageSlug) {
      if (isLoading) {
          return (
             <div className="flex items-center justify-center min-h-[60vh]">
                 <div className="w-10 h-10 border-4 border-brand-500 border-t-transparent rounded-full animate-spin"></div>
             </div>
          );
      }

      if (!activePage) {
          return (
             <div className="min-h-[50vh] flex flex-col items-center justify-center">
                 <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">404 - Not Found</h2>
                 <Link href="/legal" className="text-brand-600 hover:underline">
                    {t('center_title')}
                 </Link>
             </div>
          );
      }

      return (
        <div className="max-w-4xl mx-auto px-4 py-12">
           <Link href="/legal" className="inline-flex items-center gap-2 text-sm text-gray-500 hover:text-brand-600 mb-8 transition-colors">
               <ArrowRight className="rotate-180" size={16} />
               {t('center_title')}
           </Link>

          <div className="bg-white dark:bg-gray-900 rounded-3xl shadow-xl overflow-hidden border border-gray-100 dark:border-gray-800">
            <div className="p-8 md:p-12">
              {/* Header */}
              <div className="border-b border-gray-200 dark:border-gray-800 pb-8 mb-8">
                <h1 className="text-3xl md:text-4xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-brand-600 to-blue-600 dark:from-brand-400 dark:to-blue-400 mb-4">
                  {activePage.title}
                </h1>
                <div className="flex items-center gap-4 text-sm text-gray-500 dark:text-gray-400">
                  <span>{t('version')} {activePage.version}</span>
                  <span>•</span>
                  <span>{t('last_updated')}: {new Date(activePage.updated_at).toLocaleDateString()}</span>
                </div>
              </div>

              {/* Styled Content */}
              <article className="prose dark:prose-invert max-w-none 
                  prose-headings:font-bold prose-headings:tracking-tight 
                  prose-headings:!mt-6 prose-headings:!mb-4
                  prose-a:text-brand-600 dark:prose-a:text-brand-400 hover:prose-a:text-brand-500 
                  prose-img:rounded-2xl prose-hr:border-gray-200 dark:prose-hr:border-gray-800
                  prose-p:leading-relaxed prose-p:mb-4
                  prose-ul:list-disc prose-ul:pl-6 prose-ul:mb-4
                  prose-ol:list-decimal prose-ol:pl-6 prose-ol:mb-4
                  prose-li:mb-1
                  whitespace-pre-wrap">
                <ReactMarkdown remarkPlugins={[remarkGfm]}>{activePage.content}</ReactMarkdown>
              </article>
            </div>
          </div>
        </div>
      );
  }

  // View: Index List
  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 pb-20">
       {/* Hero Section */}
       <div className="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 py-16 md:py-24 relative overflow-hidden">
          <div className="absolute top-0 left-0 w-full h-full opacity-30 dark:opacity-10 pointer-events-none bg-[radial-gradient(circle_at_top_right,_var(--tw-gradient-stops))] from-brand-100 via-transparent to-transparent"></div>
          
          <div className="max-w-7xl mx-auto px-6 relative z-10 text-center">
             <div className="inline-flex items-center justify-center p-3 bg-brand-50 dark:bg-brand-500/10 rounded-2xl mb-6 text-brand-600 dark:text-brand-400">
                <Scale size={32} />
             </div>
             <h1 className="text-4xl md:text-5xl font-black text-gray-900 dark:text-white mb-6 tracking-tight">
                {t('center_title')}
             </h1>
             <p className="text-xl text-gray-600 dark:text-gray-400 max-w-2xl mx-auto">
                {t('center_desc')}
             </p>
          </div>
       </div>

       {/* Content Section */}
       <div className="max-w-5xl mx-auto px-6 py-12 -mt-10 relative z-20">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
             {isLoading ? (
                <div className="col-span-full py-20 text-center">
                   <div className="w-10 h-10 border-4 border-brand-500 border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
                   <p className="text-gray-500">{t('loading_docs')}</p>
                </div>
             ) : (
                 <>
                    {pages.map((page) => (
                        <Link 
                           key={page.slug} 
                           href={`/legal?page=${page.slug}`} // New URL structure
                           className="group bg-white dark:bg-gray-800 p-8 rounded-3xl border border-gray-100 dark:border-gray-700 shadow-sm hover:shadow-xl transition-all duration-300 flex items-center justify-between"
                        >
                           <div className="flex items-center gap-4">
                              <div className="w-12 h-12 rounded-2xl bg-gray-50 dark:bg-gray-700 flex items-center justify-center text-gray-500 dark:text-gray-400 group-hover:bg-brand-50 dark:group-hover:bg-brand-500/20 group-hover:text-brand-600 dark:group-hover:text-brand-400 transition-colors">
                                 <FileText size={20} />
                              </div>
                              <div>
                                 <h2 className="text-lg font-bold text-gray-900 dark:text-white group-hover:text-brand-600 dark:group-hover:text-brand-400 transition-colors">
                                    {page.title}
                                 </h2>
                                 <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                                    {t('read_full')}
                                 </p>
                              </div>
                           </div>
                           <div className="w-8 h-8 rounded-full bg-gray-50 dark:bg-gray-700 flex items-center justify-center text-gray-400 group-hover:bg-brand-600 group-hover:text-white transition-all transform group-hover:translate-x-1">
                              <ArrowRight size={14} />
                           </div>
                        </Link>
                    ))}

                    {pages.length === 0 && (
                        <div className="col-span-full text-center py-20 text-gray-500 bg-white dark:bg-gray-800 rounded-3xl border border-dashed border-gray-300 dark:border-gray-700">
                           <p>{t('no_docs')}</p>
                        </div>
                    )}
                 </>
             )}
          </div>
       </div>
    </div>
  );
}

export default function LegalIndexPage() {
    return (
        <Suspense fallback={<div>Loading...</div>}>
            <LegalContent />
        </Suspense>
    )
}
