// D:\Nextjs\latest-deployed-universitiespage-code\src\app\admin\news\edit\[id]\page.js

'use client';

import { useEffect, useState, use } from 'react';
import { useRouter } from 'next/navigation';
import { Loader2 } from 'lucide-react';
import Layout from '../../../components/Layout';
import AddNews from '../../../pages/News/AddNews';

export default function EditNews({ params }) {
  const router = useRouter();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [newsData, setNewsData] = useState(null);

  // Properly unwrap the params promise
  const { id } = use(params);

  useEffect(() => {
    let isMounted = true;

    const fetchData = async () => {
      try {
        if (!id || isNaN(parseInt(id))) {
          throw new Error('Invalid news ID');
        }

        const response = await fetch(`/api/internal/news/${id}`);
        
        if (!response.ok) {
          const errorText = await response.text();
          let errorData;
          try {
            errorData = JSON.parse(errorText);
          } catch {
            throw new Error(errorText || 'Failed to fetch news');
          }
          throw new Error(errorData.message || 'Failed to fetch news');
        }

        const result = await response.json();
        
        if (!result?.success || !result?.data) {
          throw new Error(result?.message || 'News not found');
        }

        if (isMounted) {
          setNewsData(transformNewsData(result.data));
          setError(null);
        }
      } catch (err) {
        console.error('Error loading news:', err);
        if (isMounted) {
          setError(err.message);
          setNewsData(null);
        }
      } finally {
        if (isMounted) {
          setLoading(false);
        }
      }
    };

    fetchData();

    return () => {
      isMounted = false;
    };
  }, [id]);

  const transformNewsData = (data) => {
    try {
      // Parse SEO data if it exists as a string
      let seoData = {};
      if (data.seo) {
        try {
          seoData = typeof data.seo === 'string' ? JSON.parse(data.seo) : data.seo;
        } catch {
          seoData = {};
        }
      }

      // Parse schema markup data
      let smQuestion = [''];
      let smAnswer = [''];
      
      if (data.sm_question) {
        try {
          smQuestion = typeof data.sm_question === 'string' 
            ? JSON.parse(data.sm_question) 
            : data.sm_question;
          if (!Array.isArray(smQuestion) || smQuestion.length === 0) {
            smQuestion = [''];
          }
        } catch {
          smQuestion = [''];
        }
      }

      if (data.sm_answer) {
        try {
          smAnswer = typeof data.sm_answer === 'string' 
            ? JSON.parse(data.sm_answer) 
            : data.sm_answer;
          if (!Array.isArray(smAnswer) || smAnswer.length === 0) {
            smAnswer = [''];
          }
        } catch {
          smAnswer = [''];
        }
      }

      return {
        ...data,
        // Ensure all fields exist with proper defaults
        title: data.title || '',
        slug: data.slug || '',
        author_id: data.author_id ? String(data.author_id) : '',
        description: data.description || '',
        image: data.image || '',
        is_featured: Boolean(data.is_featured),
        is_active: Boolean(data.is_active),
        enable_meta_tags: Boolean(data.enable_meta_tags),
        likes: Number(data.likes) || 0,
        
        // SEO fields
        seo: JSON.stringify(seoData),
        meta_title: seoData.meta_title || '',
        meta_description: seoData.meta_description || '',
        meta_keywords: seoData.meta_keywords || '',
        
        // Schema markup
        sm_question: JSON.stringify(smQuestion),
        sm_answer: JSON.stringify(smAnswer),
        
        // Ensure all required fields exist for the form
        created_at: data.created_at || new Date().toISOString(),
        updated_at: data.updated_at || new Date().toISOString(),
      };
    } catch (error) {
      console.error('Error transforming news data:', error);
      throw new Error('Invalid news data format');
    }
  };

  const handleBackToList = () => {
    router.push('/admin/news');
  };

  if (loading) {
    return (
      <Layout>
        <div className="flex justify-center items-center h-64">
          <Loader2 className="animate-spin h-8 w-8 text-blue-500" />
          <span className="ml-2">Loading news data...</span>
        </div>
      </Layout>
    );
  }

  if (error) {
    return (
      <Layout>
        <div className="flex flex-col items-center justify-center h-64 gap-4">
          <p className="text-red-500 text-lg">{error}</p>
          <button
            onClick={handleBackToList}
            className="px-4 py-2 bg-linear-to-b from-[#0B6D76] to-[#094F56] text-white rounded hover:from-[#094F56] hover:to-[#083a40] transition-colors"
          >
            Back to News List
          </button>
        </div>
      </Layout>
    );
  }

  if (!newsData) {
    return (
      <Layout>
        <div className="flex flex-col items-center justify-center h-64 gap-4">
          <p className="text-red-500 text-lg">News data could not be loaded</p>
          <button
            onClick={handleBackToList}
            className="px-4 py-2 bg-linear-to-b from-[#0B6D76] to-[#094F56] text-white rounded hover:from-[#094F56] hover:to-[#083a40] transition-colors"
          >
            Back to News List
          </button>
        </div>
      </Layout>
    );
  }

  return (
    <Layout>
      <AddNews 
        id={id} 
        isEditMode={true} 
        initialData={newsData}
        onSuccess={handleBackToList}
      />
    </Layout>
  );
}