"use client";

import { useRouter, useParams } from "next/navigation";

import UploadQuotation from "../../upload-quotation-dynamic";
import AgreementDocument from "../../agreement-document-dynamic";
import PageHeader from "@/src/components/web/ui/page-header";
import InfoTable from "@/src/components/web/ui/info-table";
import BackButton from "@/src/components/web/ui/BackButton";

import { ApplicantInfoCard, TimelineItemData, TimelineList } from "@/src/app/admin/(pages)/(application-details)/_common/timeline-components";
import ComponentCard from "@/src/components/admin/common/ComponentCard";
import { useEffect, useState } from "react";
import { getMyApplicationById, getMyApplicationTimeline } from "@/src/services/web/services";
import ProtectedApplicationRoute from "@/src/components/web/ProtectedApplicationRoute";


interface TimelineData {
  applicantName: string;
  applicationNo: string;
  submittedDate: string;
  timeline: TimelineItemData[];
}

export default function MyApplicationDetailHi() {
  const router = useRouter();
  const params = useParams();
  const [timeline, setTimeline] = useState<any | null>(null);
  const [application, setApplication] = useState<any | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function loadTimeline() {
      try {
        setLoading(true);
        setError(null);

        const appResponse = await getMyApplicationById(Number(params.id as string));
        const appData = appResponse.data?.data || appResponse.data;

        const formattedApp = {
          id: appData.id?.toString() || params.id,
          applicantName: appData.applicant_name,
          applicationNo: appData.application_no,
          applicationType: appData.application_type,
          email: appData.applicant_email,
          phone: appData.applicant_cellphone,
          address: appData.applicant_address,
          area: appData.applicant_area,
        };

        setApplication(formattedApp);

        let timelineData: TimelineData;
        try {
          const timelineResponse = await getMyApplicationTimeline(Number(params.id as string));
          const timelineResponseData = timelineResponse.data?.data || timelineResponse.data;

          timelineData = {
            applicantName: timelineResponseData?.applicantName || appData?.applicant_name || 'N/A',
            applicationNo: timelineResponseData?.applicationNo || appData?.application_no || 'N/A',
            submittedDate: formatDate(timelineResponseData?.submittedDate) || formatDate(appData?.created_on) || 'N/A',
            timeline: timelineResponseData?.timeline || []
          };
        } catch (err) {


          timelineData = {
            applicantName: appData?.applicant_name || 'N/A',
            applicationNo: appData?.application_no || 'N/A',
            submittedDate: formatDate(appData?.created_on) || 'N/A',
            timeline: []
          };
        }

        setTimeline(timelineData);
      } catch (err: any) {
        console.error('Error loading application:', err);

        if (err?.response?.status === 403) {
          setError('Access denied. You can only view your own applications.');
        } else if (err?.response?.status === 401) {
          setError('Unauthorized access. Please log in again.');
        } else if (err?.response?.status === 404) {
          setError('Application not found.');
        } else if (err?.response?.data?.message) {
          setError(err.response.data.message);
        } else if (err?.message) {
          setError(err.message);
        } else {
          setError('Failed to load application details.');
        }
      } finally {
        setLoading(false);
      }
    }

    if (params.id as string) {
      loadTimeline();
    }
  }, [params.id as string, router]);

  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 breadcrumbs = [
    { label: "Home", href: "/" },
    { label: "My Application", href: "/my-application" },
    { label: "Application Status Detail" }
  ];

  if (loading) {
    return (
      <div className="flex justify-center items-center min-h-screen bg-gray-50">
        <div className="text-center">
          <div className="animate-spin rounded-full h-16 w-16 border-b-4 border-teal-600 mx-auto mb-4"></div>
          <p className="text-gray-600 text-lg">Loading application details...</p>
        </div>
      </div>
    );
  }

  if (error || !application) {
    return (
      <div className="flex justify-center items-center min-h-screen bg-gray-50 px-4">
        <div className="max-w-md w-full bg-white rounded-2xl shadow-lg p-8 text-center">
          <div className="mb-6">
            <div className="mx-auto flex items-center justify-center h-16 w-16 rounded-full bg-red-100 mb-4">
              <svg
                className="h-8 w-8 text-red-600"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
                />
              </svg>
            </div>
            <h2 className="text-2xl font-bold text-gray-900 mb-2">
              {error?.includes('Access denied') || error?.includes('403')
                ? 'Access Denied'
                : error?.includes('Unauthorized') || error?.includes('401')
                  ? 'Unauthorized Access'
                  : 'Application Not Found'}
            </h2>
            <p className="text-gray-600 mb-6">
              {error?.includes('Access denied') || error?.includes('403')
                ? 'You do not have permission to view this application. You can only access your own applications.'
                : error?.includes('Unauthorized') || error?.includes('401')
                  ? 'Your session has expired or you are not authorized to view this content. Please log in again.'
                  : error || 'The application you are looking for does not exist or has been removed.'}
            </p>
          </div>
          <div className="space-y-3">
            <button
              onClick={() => router.push('/my-application')}
              className="w-full px-6 py-3 bg-teal-600 text-white rounded-lg hover:bg-teal-700 transition-colors font-medium"
            >
              Go to My Applications
            </button>
            <button
              onClick={() => router.push('/')}
              className="w-full px-6 py-3 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors font-medium"
            >
              Go to Home
            </button>
          </div>
        </div>
      </div>
    );
  }

  const applicantData = [
    { label: "Applicant Name", value: application.applicantName },
    { label: "Application No", value: application.applicationNo },
    { label: "Application Type", value: application.applicationType },
    { label: "Email", value: application.email },
    { label: "Phone", value: application.phone },
    { label: "Address", value: application.address || application.area || "N/A" }
  ];

  const handleDetailRedirect = (applicationId: string, applicationType: string) => {


    switch (applicationType) {
      case 'First-Time Home Buyer Assistance':
        router.push(`/first-time-home-buyer-application-form?id=${applicationId}&mode=view`);
        break;
      case 'Home Improvement Program':
        router.push(`/home-improvement-application-form?id=${applicationId}&mode=view`);
        break;
      case 'Tenant Maintenance Requests':
        router.push(`/rm-application-form?id=${applicationId}&mode=view`);
        break;
      default:
        break;
    }

  };


  return (
    <ProtectedApplicationRoute>
      <>
        <PageHeader
          title={application.applicationType}
          breadcrumbs={breadcrumbs}
        />

        <section className="w-full py-10 px-0 lg:px-10">
          <div className="max-w-7xl mx-auto">
            <div className="mb-8 flex items-start justify-between gap-4">
              <div>
                <h2 className="text-2xl font-semibold text-gray-900">
                  Application Status Detail
                </h2>
                <p className="text-gray-500 text-sm mt-1">
                  Track & manage your housing application
                </p>
              </div>
              <BackButton />
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-10 gap-6">
              <div className="lg:col-span-7 space-y-6">
                <InfoTable title="Applicant Information" data={applicantData} />

                <div className="flex items-end justify-end gap-4 mt-4">
                  <button
                    onClick={() => handleDetailRedirect(application.id, application.applicationType)}
                    className="px-5 py-2 bg-teal-600 text-white rounded-md hover:bg-teal-700" >
                    View Application
                  </button>
                </div>
                {
                  application.applicationType !== 'Tenant Maintenance Requests' &&

                  <div className="bg-white rounded-xl p-6 shadow-sm">
                    <UploadQuotation applicationId={params.id as string} />
                  </div>
                }
                <div className="bg-white rounded-xl p-6 shadow-sm">
                  <AgreementDocument applicationId={params.id as string} />
                </div>
              </div>

              <div className="lg:col-span-3">
                <>
                  <ApplicantInfoCard
                    applicantName={timeline.applicantName}
                    applicationNo={timeline.applicationNo}
                    submittedDate={timeline.submittedDate}
                  />

                  <ComponentCard
                    size="sm"
                    className="border border-gray-200 rounded-xl pb-10 mt-4"
                    title="Application Activity"
                    desc="Historical logs"
                  >
                    {timeline.timeline.length > 0 ? (
                      <TimelineList
                        items={timeline.timeline}

                      />
                    ) : (
                      <p className="text-gray-500 text-center py-8">
                        No timeline activities found
                      </p>
                    )}
                  </ComponentCard>
                </>
              </div>
            </div>

          </div>
        </section>
      </>
    </ProtectedApplicationRoute>
  );
}
