"use client";
import { useRef, useState, useEffect } from "react";
import { CheckCircle2, Circle, Loader2, XCircle, RefreshCcw } from "lucide-react";
import ComponentCard2 from "@/src/components/admin/common/ComponentCard2";
import { getApplicationTimeline } from "@/src/services/admin/services";

const StatusIcon = ({ status }: { status: string }) => {
  switch (status) {
    case "Completed": return <CheckCircle2 className="w-5 h-5 text-teal-600 fill-teal-50" />;
    case "In Progress": return <Loader2 className="w-5 h-5 text-blue-600 animate-spin" />;
    case "Rejected": return <XCircle className="w-5 h-5 text-red-600 fill-red-50" />;
    default: return <Circle className="w-5 h-5 text-gray-300 fill-white" />;
  }
};

export default function ApplicationTimeline({ data, type }: { data: any; type: string }) {
  const containerRef = useRef<HTMLDivElement>(null);
  const [timeline, setTimeline] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchTimeline = async () => {
      try {
        const res = await getApplicationTimeline(type, data.id);
        setTimeline(res.data.data || []);
      } catch (error) {
        console.error(error);
      } finally {
        setLoading(false);
      }
    };
    if (data?.id && type) fetchTimeline();
  }, [data?.id, type]);

  return (
    <>
      <div className="relative bg-white rounded-xl border border-gray-200 shadow-sm p-3.5 space-y-2">
        <h3 className="text-xl font-medium text-primary dark:text-white/90">Applicant Information</h3>
        <div className="space-y-1">
          <p className="text-sm text-gray-600 flex items-center gap-1">
            <span className="min-w-[130px]">Applicant's Name :</span>
            <strong className="text-gray-900 font-semibold truncate">{data?.applicant_name || "N/A"}</strong>
          </p>
          <p className="text-sm text-gray-600 flex items-center gap-1">
            <span className="min-w-[130px]">Applicant's No :</span>
            <strong className="text-gray-900 font-semibold truncate">{data?.application_no || "N/A"}</strong>
          </p>
          <p className="text-sm text-gray-600 flex items-center gap-1">
            <span className="min-w-[130px]">Application Submitted :</span>
            <strong className="text-gray-900 font-semibold truncate">{data?.created_on ? new Date(data.created_on).toLocaleDateString() : "N/A"}</strong>
          </p>
        </div>
      </div>

      <ComponentCard2 title="Application Activity" desc="Historical logs">
        <div ref={containerRef} className="timeline-container relative mt-4 overflow-y-auto pr-4">
          {loading ? (
            <div className="flex justify-center py-8">
              <Loader2 className="w-6 h-6 animate-spin text-gray-400" />
            </div>
          ) : timeline.length === 0 ? (
            <div className="text-center py-8 text-gray-400 text-sm">No activity yet</div>
          ) : (
            <div style={{ direction: "ltr" }}>
              <div className="absolute left-[25px] top-2 bottom-2 w-0.5 bg-gray-100" />
              <div className="space-y-4">
                {[...timeline].map((item) => {
                  const statusName = item.status?.status_name || "Pending";
                  const isRejected = statusName.toLowerCase().includes("reject");
                  const isInProgress = statusName.toLowerCase().includes("progress") || statusName.toLowerCase().includes("pending");
                  const isCompleted = statusName.toLowerCase().includes("approv") || statusName.toLowerCase().includes("complet");

                  return (
                    <div key={item.id} className="relative flex items-start group">
                      <div className="relative z-10 flex items-center justify-center bg-white p-1 ml-[-4px]">
                        <StatusIcon status={isCompleted ? "Completed" : isRejected ? "Rejected" : isInProgress ? "In Progress" : "Pending"} />
                      </div>
                      <div
                        className={`ml-4 p-4 rounded-xl border transition-all duration-200 w-full
                          ${isCompleted ? "border-teal-200 bg-teal-50/30 hover:bg-teal-50/60" : ""}
                          ${isRejected ? "border-red-200 bg-red-50/40" : ""}
                          ${isInProgress ? "border-blue-500 bg-blue-50 shadow-md ring-1 ring-blue-200" : "border-gray-100"}
                          ${!isCompleted && !isRejected && !isInProgress ? "bg-white border-dashed opacity-60" : "bg-white"}
                        `}
                      >
                        <div className="flex items-center justify-between gap-2 mb-3">
                          <span className="flex items-center gap-2">
                            <span
                              className={`px-2 py-0.5 rounded-[4px] text-[10px] font-bold tracking-wider uppercase
                                ${
                                  isCompleted
                                    ? "bg-teal-600 text-white"
                                    : isInProgress
                                    ? "bg-blue-600 text-white animate-pulse"
                                    : isRejected
                                    ? "bg-red-600 text-white"
                                    : "bg-gray-100 text-gray-400"
                                }
                              `}
                            >
                              {statusName}
                            </span>
                            {item.updated_by && (
                              <span className="text-[10px] text-gray-500">by {item.updated_by}</span>
                            )}
                            {isRejected && (
                              <button className="flex items-center gap-1 text-[10px] font-bold text-red-600 hover:text-red-800 transition-colors uppercase">
                                <RefreshCcw className="w-3 h-3" /> Re-fill App
                              </button>
                            )}
                          </span>
                          <span className="text-[10px] font-semibold text-gray-400 uppercase">
                            {new Date(item.created_on).toLocaleDateString("en-US", { day: "numeric", month: "short", year: "numeric" })} • {new Date(item.created_on).toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit" })}
                          </span>
                        </div>
                        <p className="text-xs text-gray-500 mt-1 leading-relaxed">{item.remark || "Status updated"}</p>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          )}
          <style jsx>{`
            .timeline-container::-webkit-scrollbar {
              width: 6px;
            }
            .timeline-container::-webkit-scrollbar-track {
              background: #f1f1f1;
              border-radius: 10px;
            }
            .timeline-container::-webkit-scrollbar-thumb {
              background: #cbd5e1;
              border-radius: 10px;
            }
            .timeline-container::-webkit-scrollbar-thumb:hover {
              background: #94a3b8;
            }
          `}</style>
        </div>
      </ComponentCard2>
    </>
  );
}
