"use client";

import React, { useEffect, useState } from "react";
import { useRouter, useParams } from "next/navigation";
import Image from "next/image";
import useSWR from 'swr';
import { toPersianDigitsDecimal } from '@/lib/utl/toPersianDigitsDecimal';
import { MdOutlineInvertColors } from "react-icons/md";
import { SiSpringsecurity } from "react-icons/si";
import { IoResizeSharp } from "react-icons/io5";

import {
  ArrowPathRoundedSquareIcon,
  ArrowRightIcon,
  CheckCircleIcon,
  ClipboardDocumentCheckIcon,
  TruckIcon,
  CheckIcon
} from "@heroicons/react/24/outline";
import { FaStar } from "react-icons/fa";
import { MdOutlineDocumentScanner } from "react-icons/md";
import { IoCloseCircleOutline } from "react-icons/io5";
import Link from "next/link";
import { motion, AnimatePresence } from "framer-motion";
import GlobalDigitConverter from '@/lib/utl/GlobalDigitConverter';

// ---------- Helpers ----------
const apiFetch = async (url, options = {}) =>
  fetch(url, {
    headers: { "Content-Type": "application/json" },
    credentials: "include",
    ...options,
  });

const swrFetcher = (url) => apiFetch(url).then(res => res.json());

const formatPrice = (price) => {
    if (!price) return "۰";
    return new Intl.NumberFormat('fa-IR').format(price);
};

const formatDate = (dateString) => {
  try {
    return new Intl.DateTimeFormat('fa-IR', {
      day: 'numeric',
      month: 'long',
      year: 'numeric',
    }).format(new Date(dateString));
  } catch (e) { return "تاریخ نامشخص"; }
};

// ---------- UI Components ----------
const LoadingSpinner = () => (
  <div className="flex justify-center items-center h-screen bg-white">
    <ArrowPathRoundedSquareIcon className="w-10 h-10 animate-spin text-red-600" />
  </div>
);

// هدر صفحه
const DetailHeader = ({ onBack }) => (
  <div
    className="flex flex-row-reverse items-center justify-between p-4 bg-white border-b border-gray-200 sticky top-0 z-20"
    role="banner"
  >
    <button className="text-[0.8rem] flex items-center gap-1" style={{ color: '#19bfd3' }}>
        <MdOutlineDocumentScanner className="w-4 h-4" />
        مشاهده فاکتور
    </button>
    <div className="w-8" />
    <h1 className="text-[0.9rem] font-medium text-gray-900  translate-x-7">جزئیات سفارش</h1>
    <button
      onClick={onBack}
      aria-label="بازگشت"
      className="p-1 rounded hover:bg-gray-100"
    >
      <ArrowRightIcon className="w-5 h-5 text-gray-800" />
    </button>
  </div>
);

// --- کامپوننت نوار پیشرفت (اصلاح شده) ---
const OrderProgressTracker = ({ order }) => {
  const steps = [
    { 
      id: 1, 
      label: 'دریافت سفارش', 
      // اصلاح ۱: اگر مراحل بعدی (پست یا آرشیو) انجام شده باشند، مرحله اول هم تیک میخورد
      isCompleted: order.seen || order.isOrderdGot || order.isDeliveredPost || order.isArchived 
    },
    { 
      id: 2, 
      label: 'تحویل به پست', 
      // اصلاح ۲: اگر آرشیو (تحویل مشتری) شده باشد، یعنی حتما پست هم شده است
      isCompleted: order.isDeliveredPost || order.isArchived 
    },
    { 
      id: 3, 
      label: 'تحویل به مشتری', 
      isCompleted: order.isArchived 
    },
  ];

  const activeStepFind = steps.find(s => !s.isCompleted);
  
  // اصلاح ۳: اگر همه مراحل تمام شده باشند، activeStep را null میکنیم تا آخری قرمز نماند
  const activeStep = activeStepFind ? activeStepFind.id : null;
  
  const completedSteps = steps.filter(s => s.isCompleted).length;
  let progressWidth = "0%";
  if (completedSteps === 1) {
    progressWidth = "50%";
  } else if (completedSteps >= 2) {
    progressWidth = "100%";
  }
  
  const allDone = completedSteps === 3;

  return (
    <div className="p-6 bg-white border-b border-gray-200">
      <h3 className="text-lg font-bold text-gray-900 mb-8 text-center">وضعیت سفارش</h3>
      <div className="flex items-center justify-between px-2">
        {steps.map((step, index) => {
          const isCompleted = step.isCompleted;
          const isActive = step.id === activeStep;
          
          return (
            <React.Fragment key={step.id}>
              {index > 0 && (
                <div className="flex-1 h-1.5 bg-gray-200 relative mx-1">
                  <motion.div 
                    className={`absolute top-0 right-0 h-1.5 rounded-full ${allDone ? 'bg-green-500' : 'bg-red-500'}`}
                    initial={{ width: 0 }}
                    animate={{ width: steps[index - 1].isCompleted ? '100%' : '0%' }}
                    transition={{ type: "spring", stiffness: 100, damping: 20, delay: 0.5 + index * 0.2 }}
                  />
                </div>
              )}
              <div className="flex flex-col items-center z-10">
                <motion.div
                  className={`w-10 h-10 rounded-full flex items-center justify-center font-bold text-lg transition-colors duration-300
                    ${isCompleted ? (allDone ? 'bg-green-500 text-white' : 'bg-red-400 text-white') : ''}
                    ${isActive ? 'bg-white border-2 border-red-500 text-red-500' : ''}
                    ${!isActive && !isCompleted ? 'bg-gray-100 text-gray-400 border-2 border-gray-50' : ''}
                  `}
                  animate={isActive ? { scale: [1, 1.1, 1] } : { scale: 1 }}
                  transition={isActive ? { duration: 1.5, repeat: Infinity, ease: "easeInOut" } : {}}
                >
                  <AnimatePresence mode="wait">
                    {isCompleted ? (
                      <motion.div
                        key="check"
                        initial={{ opacity: 0, scale: 0.5 }}
                        animate={{ opacity: 1, scale: 1 }}
                        exit={{ opacity: 0, scale: 0.5 }}
                      >
                        <CheckIcon className="w-6 h-6" />
                      </motion.div>
                    ) : (
                      <motion.span key="number" initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
                        {step.id}
                      </motion.span>
                    )}
                  </AnimatePresence>
                </motion.div>
                <span className={`mt-3 text-xs font-medium whitespace-nowrap
                  ${isActive ? 'text-red-600 font-bold' : 'text-gray-500'}
                  ${isCompleted ? 'text-gray-700' : ''}
                `}>
                  {step.label}
                </span>
              </div>
            </React.Fragment>
          );
        })}
      </div>
    </div>
  );
};

// کامپوننت نمایش اطلاعات محصول
const OrderProductInfo = ({ order }) => (
  <div className="p-4 bg-white border-b border-gray-200">
    <div className="flex gap-4">
      <div className="w-24 h-24 relative flex-shrink-0">
        <Image
          src={`https://www.atenakala.com/${order.image}`}
          alt={order.productTitle}
          fill
          className="object-cover rounded-lg border border-gray-100"
          onError={(e) => { e.target.onerror = null; e.target.src="https://placehold.co/100x100/f0f0f0/ccc?text=Img"; }}
        />
      </div>
      <div className="space-y-1.5 text-[0.8rem]">
        <h3 className="font-bold text-gray-800 text-sm leading-6 !mb-0">{order.productTitle}</h3>
        {order.productColor !== 'freeColor' && (
            <div className="flex flex-row items-center font-normal text-[0.75rem] text-neutral-400 mt-3">
                <MdOutlineInvertColors className=" ml-1"/>
                <p>رنگ: {order.productColor}</p>
            </div>
        )}
        {order.productSize !== 'freeSize' && (
            <div className="flex flex-row items-center font-normal text-[0.75rem] text-neutral-400 mt-3">
                <IoResizeSharp  className=" ml-1"/>
                <p>سایز: {order.productSize}</p>
            </div>
        )}
        <div className="flex flex-row items-center font-normal text-[0.75rem] text-neutral-400 mt-3">
            <SiSpringsecurity className=" ml-1"/>
            <p>گارانتی اصالت محصول</p>
        </div>
      </div>
    </div>
  </div>
);

// کامپوننت ردیف اطلاعات
const InfoRow = ({ label, value, valueClass = "font-medium" }) => (
  <div className="flex justify-between items-center py-3 text-[0.75rem] px-3">
    <span className="text-gray-500 font-medium">{label}</span>
    <span className={`${valueClass} text-neutral-700`} dir="ltr">{value}</span>
  </div>
);

// کامپوننت اطلاعات پرداخت
const OrderPaymentInfo = ({ order }) => {
  const totalPrice = order.productPrice + (order.productShippingCost || 0);

  return (
    <div className="p-4 bg-white border-b border-gray-200">
      <div className="space-y-2 divide-y divide-gray-100">
        <InfoRow label="مبلغ" value={`${formatPrice(order.productPrice)} تومان`} />
        <InfoRow label="نوع پرداخت" value={order.howPaid} />
        <InfoRow label="هزینه ارسال" value={`پس کرایه`} />
        
        {/* --- بخش جدید اضافه شده: وضعیت پرداخت --- */}
        <InfoRow 
            label="وضعیت پرداخت" 
            value={order.isPaid ? "سفارش پرداخت شده است" : "پرداخت نشده است"} 
            valueClass={order.isPaid ? "!text-green-600 font-bold" : "text-red-600 font-bold"}
        />
        
      </div>
    </div>
  );
};

function PersianDateDisplay(baseDate, daysToAdd) {
  if (!baseDate || typeof daysToAdd !== "number") return "ورودی نامعتبر";

  try {
    const date = new Date(
      typeof baseDate === "string" && !baseDate.endsWith("Z")
        ? baseDate + "Z"
        : baseDate
    );

    if (isNaN(date.getTime())) return "تاریخ نامعتبر";

    date.setDate(date.getDate() + daysToAdd);

    const formatter = new Intl.DateTimeFormat("fa-IR", {
      weekday: "long",
      month: "long",
      day: "numeric",
      timeZone: "Asia/Tehran",
    });

    return formatter.format(date);
  } catch (error) {
    console.error("Error converting date:", error);
    return "تاریخ نامعتبر";
  }
}

// کامپوننت وضعیت مرسوله
const TrackingSection = ({ order }) => {
  const [isCopied, setIsCopied] = useState(false);

  const handleCopy = () => {
    if (!order.postSystemCode || isCopied) return;

    navigator.clipboard.writeText(order.postSystemCode)
      .then(() => {
        setIsCopied(true);
        setTimeout(() => {
          setIsCopied(false);
        }, 3000); 
      })
      .catch(err => {
        console.error('خطا در کپی کردن: ', err);
        alert("خطا در کپی کردن کد رهگیری");
      });
  };

  return (
    <div className="py-4 px-2 bg-white border-b border-gray-200 space-y-4">
      {order.isArchived === true && ( 
        <div className="bg-green-100 text-green-700 p-3 rounded-lg flex items-center gap-2">
          <CheckCircleIcon className="w-5 h-5" />
          <span className="text-sm font-medium">تحویل مرسوله به مشتری</span>
        </div>
      )}
      
      <div className="border-gray-200 rounded-lg p-3 space-y-3" style={{ backgroundColor: "rgba(25, 191, 211, .07)" }}>
        <p className="text-xs text-gray-600 leading-6 mb-8">
          با استفاده از سامانه رهگیری پست می‌توانید از وضعیت مرسوله باخبر شوید.
        </p>
        {order.shippingCompany === "mahax"?<Link href={`https://mahex.com/tracking`} target="_blank" rel="noopener noreferrer"  className="text-[0.8rem] font-medium mt-4" style={{ color: '#19bfd3' }}>
          ورود به سامانه رهگیری ›
        </Link>:
        order.shippingCompany === "dekapost"?<Link href={`https://dekapost.com/`} target="_blank" rel="noopener noreferrer"  className="text-[0.8rem] font-medium mt-4" style={{ color: '#19bfd3' }}>
          ورود به سامانه رهگیری ›
        </Link>:
        order.shippingCompany === "tipax"?<Link href={`https://tipaxco.com/`} target="_blank" rel="noopener noreferrer"  className="text-[0.8rem] font-medium mt-4" style={{ color: '#19bfd3' }}>
          ورود به سامانه رهگیری ›
        </Link>:
        order.shippingCompany === "pishtaz"?<Link href={`https://tracking.post.ir/search.aspx?id=${order.postSystemCode}`} target="_blank" rel="noopener noreferrer"  className="text-[0.8rem] font-medium mt-4" style={{ color: '#19bfd3' }}>
          ورود به سامانه رهگیری ›
        </Link>:null
        }

        <div 
          onClick={handleCopy} 
          className="flex justify-between items-center gap-2 pt-1 text-[0.8rem] text-neutral-700 cursor-pointer group mt-2"
        >
          <span>کد رهگیری:</span>
          <div className="flex flex-row items-center">
            <span className="text-[0.8rem] font-medium ml-1 group-hover:text-blue-600 transition-colors"> 
              {order.postSystemCode || "کد رهگیری ثبت نشده"}
            </span>
            {isCopied ? (
              <span className="text-[0.7rem] font-medium px-1" style={{ color: '#19bfd3' }}>کپی شد!</span>
            ) : (
              <ClipboardDocumentCheckIcon className="w-5 h-5 text-gray-500 group-hover:text-blue-600 transition-colors" />
            )}
          </div>
        </div>
        
      </div>
      
      <InfoRow label="شماره باربر" value={order.senderNumber || "ثبت نشده"} />
      <InfoRow label="زمان تحویل" value={`از ${PersianDateDisplay(order.dateRecived,4)} تا ${PersianDateDisplay(order.dateRecived,6)}`} />
      <InfoRow label="هزینه ارسال" value={`پس کرایه`} />
      <InfoRow label="مبلغ مرسوله" value={`${formatPrice(order.productPrice)} تومان`} />
    </div>
  );
};

// کامپوننت امتیازدهی
const RatingSection = () => (
  <div className="p-4 bg-white border-b border-gray-200">
    <div className="flex justify-between items-center mb-3">
      <span className="font-medium text-gray-800">امتیاز دهید!</span>
      <div className="flex flex-row-reverse gap-1" dir="ltr">
        {[5, 4, 3, 2, 1].map(star => (
          <FaStar key={star} className="w-6 h-6 text-gray-300 cursor-pointer hover:text-yellow-400 transition-colors" />
        ))}
      </div>
    </div>
    <div className="w-full text-center py-3 border border-red-500 text-red-500 rounded-lg font-bold hover:bg-red-50 transition-colors">
      ثبت دیدگاه
    </div>
  </div>
);

// ---------- صفحه اصلی جزئیات سفارش ----------
export default function OrderDetailPage() {
  const router = useRouter();
  const params = useParams();
  const { orderId } = params;

  const { data: userData, error: userError, isLoading: authLoading } = useSWR(
    '/api/auth/me', 
    swrFetcher
  );
  
  const { data: orderData, error: orderError, isLoading: orderLoading } = useSWR(
    orderId ? `/api/orders/${orderId}` : null, 
    swrFetcher
  );
  
  const order = orderData?.order;

  useEffect(() => {
    if (!authLoading && userError) {
      router.push("/login");
    }
  }, [authLoading, userError, router]);


  if (authLoading || orderLoading) return <LoadingSpinner />;
  
  if (orderError || !order) {
    return (
      <div className="max-w-lg mx-auto bg-white h-screen flex flex-col" dir="rtl">
        <DetailHeader onBack={() => router.back()} />
        <div className="flex-1 flex flex-col items-center justify-center text-center p-16">
          <IoCloseCircleOutline className="w-16 h-16 text-red-400 mb-4" />
          <p className="text-base font-medium text-gray-700">
            {orderError ? "خطا در دریافت اطلاعات لطفا صفحه را رفرش نمایید." : " سفارش یافت نشد لطفا صفحه را رفرش نمایید."}
          </p>
        </div>
      </div>
    );
  }
  
  return (
    <div className="min-h-screen bg-gray-100 font-normal" dir="rtl">
      <GlobalDigitConverter/>
      <div className="bg-white shadow-lg md:shadow-xl md:my-8 rounded-lg overflow-hidden pb-4">
        
        <DetailHeader onBack={() => router.back()} />

        {/* نوار پیشرفت */}
        <OrderProgressTracker order={order} />
        
        <main>
          {/* بخش ۱: جزئیات سفارش */}
          <div className="p-4 bg-white border-b border-gray-200">
            <div className="space-y-2 divide-y divide-gray-100">
              <div className="flex justify-between items-center py-3 text-[0.75rem] px-3">
                <span className="text-gray-500 font-medium">آخرین وضعیت محصول</span>
                <span className="font-semibold text-emerald-500 text-[0.75rem]" dir="ltr">{order.productShippingStatu}</span>
              </div>
              <InfoRow label="کد پیگیری سفارش" value={order.OrderCode} valueClass="text-gray-800 font-bold" />
              <InfoRow label="تاریخ ثبت سفارش" value={`${PersianDateDisplay(order.dateRecived,0)}`} />
              <InfoRow label="تحویل گیرنده" value={order.customerFullName} />
              <InfoRow label="شماره موبایل" value={order.customerConntactWay} />
              <div className="py-3">
                <span className="text-sm text-gray-500">آدرس</span>
                <p className="text-sm text-gray-800 font-medium leading-6 mt-2">{order.customerExactAddress}</p>
              </div>
            </div>
          </div>
          
          {/* بخش ۲: اطلاعات پرداخت */}
          <OrderPaymentInfo order={order} />

          {/* بخش ۳: مرسوله */}
          <div className="p-4 bg-white border-b border-gray-200">
            <div className="flex justify-between items-center mb-3">
              <h3 className="font-bold text-gray-900">مرسوله ۱ از ۱</h3>
              <div className="flex items-center gap-2 text-sm text-gray-600">
                <TruckIcon className="w-5 h-5 text-yellow-600" />
                <span>ارسال با {order.shippingCompany}</span>
              </div>
            </div>
          </div>
          
          <TrackingSection order={order} />
          
          <OrderProductInfo order={order} />
          
          <RatingSection />

        </main>
      </div>
    </div>
  );
}