/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import React, { useState, useEffect } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import {
  formatDate,
  formatTime,
  formatSpaceForText,
} from "../../../lib/Helper";
import { getPublicOrderTracking } from "../../../Api/OrderApi";
import HourGlassLoader from "../../Loader/Loader";

export default function PublicOrderTracking() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const [trackingId, setTrackingId] = useState(
    searchParams.get("tracking_id") || "",
  );
  const [trackingHistory, setTrackingHistory] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [hasSearched, setHasSearched] = useState(false);

  const fetchOrderDetails = async (id: string) => {
    if (!id) return;
    setIsLoading(true);
    setError(null);
    setHasSearched(true);
    try {
      const response = await getPublicOrderTracking(id);
      // The API returns an array of tracking events in 'data'
      if (Array.isArray(response) && response.length > 0) {
        // Sort by date descending (newest first)
        const sortedHistory = [...response].sort(
          (a, b) =>
            new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
        );
        setTrackingHistory(sortedHistory);
      } else {
        setTrackingHistory([]);
        setError("No order found with this tracking ID.");
      }
    } catch (err) {
      console.error("Error fetching order details:", err);
      setError("An error occurred while fetching order details.");
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    const id = searchParams.get("tracking_id");
    if (id) {
      setTrackingId(id);
      fetchOrderDetails(id);
    }
  }, [searchParams]);

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    if (trackingId.trim()) {
      router.push(`/track-order?tracking_id=${trackingId.trim()}`);
      fetchOrderDetails(trackingId.trim());
    }
  };

  return (
    <div className="public-tracking-container">
      <header className="public-header">
        <div className="header-content">
          <Link href="/" className="logo-link">
            <Image
              src="/images/app/logo_white.png"
              alt="Delybell Logo"
              className="header-logo-img"
              width={120}
              height={40}
            />
          </Link>
          <div className="header-actions">
            {/* <Link href="/dashboard" className="login-link">
              <i className="ri-user-line"></i>
              <span>Login</span>
            </Link> */}
          </div>
        </div>
      </header>

      <style jsx>{`
        .public-header {
          position: fixed;
          top: 0;
          left: 0;
          right: 0;
          height: 70px;
          background: #752f8a;
          display: flex;
          align-items: center;
          z-index: 1000;
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .header-content {
          max-width: 1200px;
          margin: 0 auto;
          width: 100%;
          padding: 0 24px;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .header-logo-img {
          height: 32px !important;
          width: auto !important;
          object-fit: contain;
          display: block;
        }

        .login-link {
          color: white;
          text-decoration: none;
          font-weight: 700;
          font-size: 0.95rem;
          display: flex;
          align-items: center;
          gap: 10px;
          padding: 10px 24px;
          border-radius: 14px;
          background: rgba(255, 255, 255, 0.15);
          border: 1px solid rgba(255, 255, 255, 0.3);
          transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
          backdrop-filter: blur(4px);
        }

        .login-link:hover {
          background: white;
          color: #752f8a;
          transform: translateY(-2px);
          box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
          border-color: white;
        }

        .login-link i {
          font-size: 1.2rem;
        }

        .public-tracking-container {
          min-height: 100vh;
          background: #f0f4f8;
          padding: 120px 20px 80px;
          font-family: "Outfit", sans-serif;
          background-image:
            radial-gradient(
              at 0% 0%,
              rgba(117, 47, 138, 0.05) 0px,
              transparent 50%
            ),
            radial-gradient(
              at 100% 0%,
              rgba(117, 47, 138, 0.05) 0px,
              transparent 50%
            );
        }

        .search-section {
          max-width: 800px;
          margin: 0 auto 60px;
          text-align: center;
          animation: fadeInDown 0.8s ease-out;
        }

        @keyframes fadeInDown {
          from {
            opacity: 0;
            transform: translateY(-20px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }

        .search-section h1 {
          font-size: 3.5rem;
          font-weight: 900;
          color: #1e293b;
          margin-bottom: 10px;
          letter-spacing: -2px;
          background: linear-gradient(135deg, #752f8a 0%, #5a2470 100%);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
        }

        .search-section p {
          font-size: 1.2rem;
          color: #64748b;
          margin-bottom: 40px;
          font-weight: 400;
        }

        .search-box-wrapper {
          position: relative;
          max-width: 600px;
          margin: 0 auto;
          padding: 10px;
          background: white;
          border-radius: 24px;
          box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.1);
          transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
          border: 1px solid rgba(226, 232, 240, 0.8);
        }

        .search-box-wrapper:focus-within {
          transform: translateY(-4px);
          box-shadow: 0 40px 80px -15px rgba(117, 47, 138, 0.15);
          border-color: #752f8a;
        }

        .search-form {
          display: flex;
          align-items: center;
          gap: 10px;
        }

        .search-input-container {
          flex: 1;
          display: flex;
          align-items: center;
          padding-left: 20px;
          color: #94a3b8;
        }

        .search-input {
          width: 100%;
          border: none;
          padding: 15px 15px;
          font-size: 1.2rem;
          font-weight: 500;
          outline: none;
          color: #1e293b;
          background: transparent;
        }

        .search-input::placeholder {
          color: #94a3b8;
          font-weight: 400;
        }

        .search-button {
          background: #752f8a;
          color: white;
          border: none;
          padding: 16px 32px;
          border-radius: 18px;
          font-weight: 700;
          font-size: 1rem;
          cursor: pointer;
          transition: all 0.3s ease;
          display: flex;
          align-items: center;
          gap: 10px;
          box-shadow: 0 10px 15px -3px rgba(117, 47, 138, 0.3);
        }

        .search-button:hover {
          background: #5a2470;
          transform: scale(1.02);
          box-shadow: 0 20px 25px -5px rgba(117, 47, 138, 0.4);
        }

        .search-button:active {
          transform: scale(0.98);
        }

        .results-container {
          max-width: 900px;
          margin: 0 auto;
          animation: fadeInUp 0.8s ease-out;
        }

        @keyframes fadeInUp {
          from {
            opacity: 0;
            transform: translateY(40px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }

        .tracking-header {
          background: white;
          padding: 40px;
          border-radius: 30px 30px 0 0;
          border-bottom: 2px dashed #f1f5f9;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .tracking-id-badge {
          background: #f8fafc;
          padding: 12px 24px;
          border-radius: 16px;
          border: 1px solid #e2e8f0;
        }

        .tracking-id-label {
          font-size: 0.75rem;
          font-weight: 700;
          color: #64748b;
          text-transform: uppercase;
          letter-spacing: 1.5px;
          margin-bottom: 4px;
        }

        .tracking-id-value {
          font-size: 1.5rem;
          font-weight: 800;
          color: #1e293b;
          margin: 0;
        }

        .current-status {
          text-align: right;
        }

        .status-pill {
          display: inline-flex;
          align-items: center;
          gap: 8px;
          padding: 10px 20px;
          border-radius: 99px;
          font-weight: 700;
          font-size: 0.9rem;
          text-transform: uppercase;
          background: #f3e8ff;
          color: #752f8a;
        }

        .timeline-card {
          background: white;
          padding: 50px 40px;
          border-radius: 0 0 30px 30px;
          box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.05);
        }

        .timeline {
          position: relative;
        }

        .timeline-item {
          display: flex;
          gap: 40px;
          margin-bottom: 50px;
          position: relative;
        }

        .timeline-item:not(:last-child)::after {
          content: "";
          position: absolute;
          left: 29px;
          top: 60px;
          bottom: -50px;
          width: 3px;
          background: linear-gradient(to bottom, #e2e8f0, transparent);
        }

        .timeline-marker {
          width: 60px;
          height: 60px;
          border-radius: 20px;
          background: #f8fafc;
          border: 2px solid #e2e8f0;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 1.5rem;
          z-index: 1;
          transition: all 0.4s ease;
          flex-shrink: 0;
          color: #94a3b8;
        }

        .timeline-item.latest .timeline-marker {
          background: #752f8a;
          border-color: #752f8a;
          color: white;
          box-shadow: 0 15px 30px rgba(117, 47, 138, 0.25);
          transform: scale(1.1);
        }

        .timeline-content {
          flex: 1;
        }

        .timeline-date {
          font-size: 0.9rem;
          font-weight: 700;
          color: #752f8a;
          margin-bottom: 8px;
          display: flex;
          align-items: center;
          gap: 6px;
        }

        .timeline-details-card {
          background: #f8fafc;
          padding: 24px;
          border-radius: 24px;
          border: 1px solid #f1f5f9;
          transition: all 0.3s ease;
        }

        .timeline-item.latest .timeline-details-card {
          background: white;
          border-color: #752f8a;
          box-shadow: 0 10px 20px rgba(0, 0, 0, 0.02);
        }

        .status-name {
          font-size: 1.25rem;
          font-weight: 800;
          color: #1e293b;
          margin-bottom: 10px;
        }

        .status-desc {
          font-size: 1.05rem;
          color: #475569;
          line-height: 1.6;
          margin-bottom: 15px;
        }

        .time-badge {
          display: inline-flex;
          align-items: center;
          gap: 6px;
          padding: 6px 14px;
          background: white;
          border-radius: 10px;
          font-size: 0.85rem;
          font-weight: 600;
          color: #64748b;
          border: 1px solid #e2e8f0;
        }

        .error-card {
          background: white;
          padding: 40px;
          border-radius: 24px;
          text-align: center;
          border: 2px solid #fee2e2;
          box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.05);
        }

        .error-icon {
          font-size: 3rem;
          color: #ef4444;
          margin-bottom: 20px;
        }

        .error-text {
          font-size: 1.2rem;
          font-weight: 600;
          color: #1e293b;
          margin-bottom: 10px;
        }

        .error-subtext {
          color: #64748b;
        }

        @media (max-width: 768px) {
          .search-section h1 {
            font-size: 2.5rem;
          }
          .tracking-header {
            flex-direction: column;
            gap: 20px;
            text-align: center;
          }
          .current-status {
            text-align: center;
          }
          .timeline-item {
            gap: 20px;
          }
          .timeline-marker {
            width: 50px;
            height: 50px;
            font-size: 1.2rem;
          }
          .timeline-item:not(:last-child)::after {
            left: 24px;
          }
        }
      `}</style>

      {isLoading && <HourGlassLoader />}

      <div className="search-section">
        <h1>Track Order</h1>
        <p>
          Enter your tracking number to see the latest updates on your shipment.
        </p>

        <div className="search-box-wrapper">
          <form onSubmit={handleSearch} className="search-form">
            <div className="search-input-container">
              <i
                className="ri-search-2-line"
                style={{ fontSize: "1.4rem" }}
              ></i>
              <input
                type="text"
                className="search-input"
                placeholder="Tracking ID (e.g. 11060200000714)"
                value={trackingId}
                onChange={(e) => setTrackingId(e.target.value)}
              />
            </div>
            <button type="submit" className="search-button">
              <span>Track Now</span>
              <i className="ri-arrow-right-line"></i>
            </button>
          </form>
        </div>
      </div>

      <div className="results-container">
        {error && (
          <div className="error-card">
            <div className="error-icon">
              <i className="ri-error-warning-line"></i>
            </div>
            <div className="error-text">{error}</div>
            <div className="error-subtext">
              Please double-check your tracking ID and try again.
            </div>
          </div>
        )}

        {trackingHistory.length > 0 && (
          <div className="tracking-result">
            <div className="tracking-header">
              <div className="tracking-id-badge">
                <p className="tracking-id-label">Shipment ID</p>
                <h2 className="tracking-id-value">{trackingId}</h2>
              </div>
              <div className="current-status">
                <div className="status-pill">
                  <i className="ri-checkbox-circle-fill"></i>
                  {formatSpaceForText(trackingHistory[0]?.status?.name) ||
                    "In Progress"}
                </div>
              </div>
            </div>

            <div className="timeline-card">
              <div className="timeline">
                {trackingHistory.map((item, index) => (
                  <div
                    key={item.id}
                    className={`timeline-item ${index === 0 ? "latest" : ""}`}
                  >
                    <div className="timeline-marker">
                      {index === 0 ? (
                        <i className="ri-map-pin-2-fill"></i>
                      ) : (
                        <i className="ri-checkbox-circle-line"></i>
                      )}
                    </div>
                    <div className="timeline-content">
                      <div className="timeline-date">
                        <i className="ri-calendar-event-line"></i>
                        {formatDate(item.createdAt)}
                      </div>
                      <div className="timeline-details-card">
                        <div className="status-name">
                          {formatSpaceForText(item.status?.name)}
                        </div>
                        <div className="status-desc">
                          {item.trackingDetails}
                        </div>
                        <div className="time-badge">
                          <i className="ri-time-line"></i>
                          {formatTime(item.createdAt)}
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}

        {!isLoading &&
          !error &&
          trackingHistory.length === 0 &&
          hasSearched && (
            <div className="error-card">
              <div className="error-icon">
                <i className="ri-search-line"></i>
              </div>
              <div className="error-text">No results found</div>
              <div className="error-subtext">
                We couldn&apos;t find any tracking information for this ID.
              </div>
            </div>
          )}
      </div>
    </div>
  );
}
