import React, { useState, useEffect } from 'react';
import { Package, Search, User as UserIcon, Clock, CheckCircle2, Copy, Check, ShieldCheck, ArrowRight, ExternalLink } from 'lucide-react';
import { useAuth } from '../context/AuthContext';
import { api } from '../services/api';
import { formatPrice, formatDate, getOrderStatusBadge, toPersianDigits } from '../utils/formatters';
import type { Order } from '../types';

interface UserProfileProps {
  initialSearchOrderNumber?: string;
  onNavigateHome: () => void;
  onViewProduct?: (slugOrId: string) => void;
}

export const UserProfile: React.FC<UserProfileProps> = ({
  initialSearchOrderNumber,
  onNavigateHome,
}) => {
  const { user, openAuthModal } = useAuth();
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchQuery, setSearchQuery] = useState(initialSearchOrderNumber || '');
  const [searchedOrder, setSearchedOrder] = useState<Order | null>(null);
  const [searchError, setSearchError] = useState('');
  const [copiedKey, setCopiedKey] = useState<string | null>(null);

  // Fetch logged in user orders
  useEffect(() => {
    if (user) {
      setLoading(true);
      api.getOrders()
        .then(res => setOrders(res))
        .catch(err => console.error(err))
        .finally(() => setLoading(false));
    }
  }, [user]);

  // Initial order search
  useEffect(() => {
    if (initialSearchOrderNumber) {
      handleSearchOrder(initialSearchOrderNumber);
    }
  }, [initialSearchOrderNumber]);

  const handleSearchOrder = async (queryNum?: string) => {
    const q = queryNum || searchQuery;
    if (!q.trim()) return;
    setLoading(true);
    setSearchError('');
    try {
      const ord = await api.getOrder(q.trim());
      setSearchedOrder(ord);
    } catch (err: any) {
      setSearchedOrder(null);
      setSearchError(err.message || 'سفارشی با این شماره پیگیری یافت نشد.');
    } finally {
      setLoading(false);
    }
  };

  const copyKey = (text: string) => {
    navigator.clipboard.writeText(text);
    setCopiedKey(text);
    setTimeout(() => setCopiedKey(null), 2000);
  };

  return (
    <div className="py-10 max-w-5xl mx-auto px-4 sm:px-6 text-right space-y-8">
      
      {/* Header & Breadcrumb */}
      <div className="flex items-center justify-between border-b border-purple-900/40 pb-5">
        <div>
          <h1 className="text-2xl sm:text-3xl font-black text-white">
            پیگیری سفارش‌ها و حساب کاربری
          </h1>
          <p className="text-xs sm:text-sm text-zinc-400 mt-1">
            مشاهده وضعیت لحظه‌ای سفارش، لایسنس‌های تحویل داده شده و اطلاعات کاربری
          </p>
        </div>

        <button
          onClick={onNavigateHome}
          className="px-4 py-2 rounded-xl bg-[#140c28] border border-purple-500/20 text-xs text-zinc-300 hover:text-white transition-colors flex items-center gap-1.5"
        >
          <span>بازگشت به صفحه اصلی</span>
          <ArrowRight className="w-4 h-4" />
        </button>
      </div>

      {/* User Info Bar if Logged in */}
      {user ? (
        <div className="p-5 rounded-2xl bg-[#140c2a] border border-purple-500/20 flex flex-wrap items-center justify-between gap-4">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 rounded-xl bg-gradient-to-tr from-purple-600 to-indigo-600 flex items-center justify-center text-white font-bold text-lg">
              {user.name.charAt(0)}
            </div>
            <div>
              <div className="flex items-center gap-2">
                <span className="font-bold text-white text-base">{user.name}</span>
                {user.role === 'admin' && (
                  <span className="text-[10px] px-2 py-0.5 rounded bg-purple-500/30 text-purple-200 border border-purple-500/40 font-bold">
                    مدیر سیستم
                  </span>
                )}
              </div>
              <div className="text-xs text-zinc-400 mt-0.5">{user.email} • {user.mobile || 'بدون شماره ثبت‌شده'}</div>
            </div>
          </div>

          <div className="flex items-center gap-2">
            <span className="text-xs text-zinc-400">تاریخ عضویت:</span>
            <span className="text-xs text-purple-300 font-medium">{formatDate(user.createdAt)}</span>
          </div>
        </div>
      ) : (
        <div className="p-4 rounded-2xl bg-[#180f33] border border-purple-500/20 flex items-center justify-between gap-4">
          <div className="text-xs sm:text-sm text-zinc-300">
            برای مشاهده سوابق کامل تمام خریدهای قبلی خود، وارد حساب کاربری شوید.
          </div>
          <button
            onClick={() => openAuthModal('login')}
            className="px-4 py-2 rounded-xl bg-purple-600 hover:bg-purple-500 text-white font-bold text-xs shrink-0"
          >
            ورود به حساب
          </button>
        </div>
      )}

      {/* Fast Order Tracking Search Box */}
      <div className="p-6 rounded-2xl bg-[#120b24] border border-purple-500/20 space-y-4">
        <h2 className="text-base font-bold text-white flex items-center gap-2">
          <Search className="w-4 h-4 text-purple-400" />
          استعلام و پیگیری سریع سفارش با کد رهگیری
        </h2>

        <form
          onSubmit={(e) => {
            e.preventDefault();
            handleSearchOrder();
          }}
          className="flex flex-col sm:flex-row gap-3"
        >
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="شماره پیگیری سفارش خود را وارد کنید (مثال: ZNA-829143)"
            className="flex-1 bg-[#0c071a] text-sm text-zinc-100 placeholder-zinc-500 px-4 py-3 rounded-xl border border-purple-500/20 focus:outline-none focus:border-purple-500 font-mono text-left"
            dir="ltr"
          />
          <button
            type="submit"
            disabled={loading}
            className="px-6 py-3 rounded-xl bg-purple-600 hover:bg-purple-500 text-white text-sm font-bold shadow-lg shadow-purple-600/30 transition-all disabled:opacity-50"
          >
            {loading ? 'در حال جستجو...' : 'استعلام وضعیت سفارش'}
          </button>
        </form>

        {searchError && (
          <div className="p-3 rounded-xl bg-rose-950/40 border border-rose-500/30 text-rose-300 text-xs">
            {searchError}
          </div>
        )}

        {/* Searched Order Result Card */}
        {searchedOrder && (
          <div className="mt-4 p-5 rounded-2xl bg-[#180f33] border border-purple-500/30 space-y-4">
            <div className="flex flex-wrap items-center justify-between gap-2 border-b border-purple-900/40 pb-3">
              <div>
                <span className="text-xs text-zinc-400">کد رهگیری: </span>
                <span className="font-mono text-sm font-bold text-purple-300">{searchedOrder.orderNumber}</span>
                <span className="text-xs text-zinc-500 mr-3">({formatDate(searchedOrder.createdAt)})</span>
              </div>

              {(() => {
                const badge = getOrderStatusBadge(searchedOrder.orderStatus);
                return (
                  <span className={`px-3 py-1 rounded-lg text-xs font-bold border ${badge.bg} ${badge.text} ${badge.border}`}>
                    {badge.label}
                  </span>
                );
              })()}
            </div>

            {/* Order Items */}
            <div className="space-y-2">
              <div className="text-xs font-bold text-zinc-400">محصولات سفارش:</div>
              {searchedOrder.items.map((item, idx) => (
                <div key={idx} className="flex items-center justify-between p-2.5 rounded-xl bg-[#0c071a] border border-purple-500/10 text-xs">
                  <div className="flex items-center gap-3">
                    <img src={item.image} alt={item.title} className="w-10 h-10 rounded-lg object-cover bg-purple-950" />
                    <div>
                      <div className="font-bold text-zinc-200">{item.title}</div>
                      <div className="text-zinc-500">{toPersianDigits(item.quantity)} عدد • {formatPrice(item.price)}</div>
                    </div>
                  </div>
                  <div className="font-bold text-purple-300">{formatPrice(item.price * item.quantity)}</div>
                </div>
              ))}
            </div>

            {/* License Keys */}
            {searchedOrder.licenseKeys && searchedOrder.licenseKeys.length > 0 && (
              <div className="p-4 rounded-xl bg-[#0c071a] border border-emerald-500/30 space-y-2">
                <div className="text-xs font-bold text-emerald-400 flex items-center gap-1.5">
                  <CheckCircle2 className="w-4 h-4" />
                  لایسنس / اکانت تحویل داده شده:
                </div>
                {searchedOrder.licenseKeys.map((key, i) => (
                  <div key={i} className="p-2.5 bg-[#170e30] rounded-lg border border-purple-500/20 flex items-center justify-between font-mono text-xs text-purple-200">
                    <span className="select-all break-all">{key}</span>
                    <button
                      onClick={() => copyKey(key)}
                      className="mr-2 p-1 px-2.5 rounded bg-purple-950 text-xs text-zinc-300 hover:text-white border border-purple-500/30"
                    >
                      {copiedKey === key ? 'کپی شد' : 'کپی لایسنس'}
                    </button>
                  </div>
                ))}
                {searchedOrder.deliveryInstructions && (
                  <div className="text-xs text-zinc-300 pt-1">
                    راهنما: {searchedOrder.deliveryInstructions}
                  </div>
                )}
              </div>
            )}

            <div className="flex justify-between items-center pt-2 border-t border-purple-900/40 text-xs">
              <span className="text-zinc-400">مبلغ پرداخت شده:</span>
              <span className="font-black text-sm text-purple-300">{formatPrice(searchedOrder.finalTotal)}</span>
            </div>
          </div>
        )}
      </div>

      {/* User Orders History */}
      {user && (
        <div className="space-y-4">
          <h2 className="text-lg font-bold text-white flex items-center gap-2">
            <Package className="w-5 h-5 text-purple-400" />
            تاریخچه سفارش‌های من ({toPersianDigits(orders.length)})
          </h2>

          {loading ? (
            <div className="py-12 text-center text-xs text-purple-300">در حال دریافت لیست سفارش‌ها...</div>
          ) : orders.length === 0 ? (
            <div className="p-8 rounded-2xl bg-[#120b24] border border-purple-500/15 text-center text-xs text-zinc-400">
              هنوز سفارشی توسط شما ثبت نشده است.
            </div>
          ) : (
            <div className="space-y-4">
              {orders.map((ord) => {
                const badge = getOrderStatusBadge(ord.orderStatus);
                return (
                  <div
                    key={ord.id}
                    className="p-5 rounded-2xl bg-[#120b24] border border-purple-500/20 hover:border-purple-500/40 transition-all space-y-3"
                  >
                    <div className="flex flex-wrap items-center justify-between gap-2 border-b border-purple-900/30 pb-3">
                      <div>
                        <span className="text-xs text-zinc-400">شماره سفارش: </span>
                        <span className="font-mono text-sm font-bold text-white">{ord.orderNumber}</span>
                        <span className="text-xs text-zinc-500 mr-3">({formatDate(ord.createdAt)})</span>
                      </div>

                      <span className={`px-3 py-1 rounded-lg text-xs font-bold border ${badge.bg} ${badge.text} ${badge.border}`}>
                        {badge.label}
                      </span>
                    </div>

                    {/* Items */}
                    <div className="space-y-1.5">
                      {ord.items.map((item, idx) => (
                        <div key={idx} className="flex items-center justify-between text-xs text-zinc-300">
                          <span>• {item.title} ({toPersianDigits(item.quantity)} عدد)</span>
                          <span className="text-zinc-400">{formatPrice(item.price * item.quantity)}</span>
                        </div>
                      ))}
                    </div>

                    {/* License if any */}
                    {ord.licenseKeys && ord.licenseKeys.length > 0 && (
                      <div className="p-3 rounded-xl bg-[#0c071a] border border-emerald-500/20 space-y-1.5">
                        <div className="text-[11px] font-bold text-emerald-400">لایسنس‌های صادر شده:</div>
                        {ord.licenseKeys.map((key, i) => (
                          <div key={i} className="flex items-center justify-between font-mono text-xs text-purple-200">
                            <span className="truncate">{key}</span>
                            <button
                              onClick={() => copyKey(key)}
                              className="text-[11px] text-purple-300 hover:text-white px-2 py-0.5 bg-purple-950 rounded border border-purple-500/30"
                            >
                              {copiedKey === key ? 'کپی شد' : 'کپی'}
                            </button>
                          </div>
                        ))}
                      </div>
                    )}

                    <div className="flex items-center justify-between pt-2 border-t border-purple-900/30 text-xs">
                      <span className="text-zinc-400">مجموع پرداختی:</span>
                      <span className="font-bold text-sm text-purple-300">{formatPrice(ord.finalTotal)}</span>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      )}

    </div>
  );
};
