"use client";

import { useState, useEffect } from "react";
import ComponentCard from "@/src/components/admin/common/ComponentCard";
import { ApplicantInfoCard, TimelineList, TimelineItemData } from "../_common/timeline-components";
import { getFTHBApplicationById, getFTHBApplicationTimeline } from "@/src/services/admin/services";

interface TimelineData {
  applicantName: string;
  applicationNo: string;
  submittedDate: string;
  timeline: TimelineItemData[];
}

interface FirstTimeHomeBuyerAssistanceTimelineProps {
  applicationId: string;
}

export default function FirstTimeHomeBuyerAssistanceTimeline({
  applicationId
}: FirstTimeHomeBuyerAssistanceTimelineProps) {
  const [data, setData] = useState<TimelineData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function loadTimeline() {
      try {
        setLoading(true);
        
        // Fetch application details
        const appResponse = await getFTHBApplicationById(Number(applicationId));
        const appData = appResponse.data?.data || appResponse.data;
        
        // Fetch timeline data
        let timelineData: TimelineData;
        try {
          const timelineResponse = await getFTHBApplicationTimeline(Number(applicationId));
          const timelineResponseData = timelineResponse.data?.data || timelineResponse.data;
          
          timelineData = {
            applicantName: timelineResponseData?.applicantName || appData?.applicantInfo?.name || 'N/A',
            applicationNo: timelineResponseData?.applicationNo || 'N/A',
            submittedDate: timelineResponseData?.submittedDate || formatDate(appData?.created_on) || 'N/A',
            timeline: timelineResponseData?.timeline || []
          };
        } catch (err) {
           
          // Fallback to basic info from application data
          timelineData = {
            applicantName: appData?.applicantInfo?.name || 'N/A',
            applicationNo: 'N/A',
            submittedDate: 'N/A',
            timeline: []
          };
        }

        setData(timelineData);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to load timeline');
      } finally {
        setLoading(false);
      }
    }

    if (applicationId) {
      loadTimeline();
    }
  }, [applicationId]);

  const formatDate = (dateString: string) => {
    if (!dateString) return 'N/A';
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', { 
      day: '2-digit', 
      month: 'short', 
      year: 'numeric' 
    });
  };

  const handleResubmit = (timelineId: number) => {
    console.log('Resubmit timeline item:', timelineId);
    // TODO: Implement resubmit functionality
  };

  if (loading) {
    return (
      <div className="space-y-4">
        <div className="bg-white rounded-xl border border-gray-200 p-3.5 animate-pulse">
          <div className="h-6 bg-gray-200 rounded w-1/3 mb-3"></div>
          <div className="space-y-2">
            <div className="h-4 bg-gray-200 rounded w-2/3"></div>
            <div className="h-4 bg-gray-200 rounded w-1/2"></div>
            <div className="h-4 bg-gray-200 rounded w-3/4"></div>
          </div>
        </div>
        <ComponentCard 
          size="sm" 
          className="border border-gray-200 rounded-xl pb-10" 
          title="Application Activity" 
          desc="Loading..."
        >
          <div className="space-y-4 mt-4">
            {[1, 2, 3].map((i) => (
              <div key={i} className="flex items-start gap-4 animate-pulse">
                <div className="w-5 h-5 bg-gray-200 rounded-full"></div>
                <div className="flex-1 space-y-2">
                  <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                  <div className="h-3 bg-gray-200 rounded w-full"></div>
                </div>
              </div>
            ))}
          </div>
        </ComponentCard>
      </div>
    );
  }

  if (error || !data) {
    return (
      <div className="bg-white rounded-xl border border-gray-200 p-6">
        <p className="text-red-600 font-semibold text-center">
          {error || 'No timeline data available'}
        </p>
      </div>
    );
  }

  return (
    <>
      <ApplicantInfoCard
        applicantName={data.applicantName}
        applicationNo={data.applicationNo}
        submittedDate={data.submittedDate}
      />

      <ComponentCard 
        size="sm" 
        className="border border-gray-200 rounded-xl pb-10" 
        title="Application Activity" 
        desc="Historical logs"
      >
        {data.timeline.length > 0 ? (
          <TimelineList 
            items={data.timeline} 
            // onResubmit={handleResubmit}
          />
        ) : (
          <div className="text-center py-8">
            <div className="text-gray-400 mb-2">
              <svg className="w-12 h-12 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
              </svg>
            </div>
            <p className="text-gray-500 text-sm">
              No timeline activities found. Timeline entries will appear here once the application is submitted.
            </p>
          </div>
        )}
      </ComponentCard>
    </>
  );
}