'use client';

import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import {
  Package,
  Truck,
  CheckCircle2,
  Clock,
  ChevronLeft,
  MapPin,
  CreditCard,
  Calendar,
  AlertCircle,
  Star,
  Loader2,
} from 'lucide-react';
import { api, getImageUrl } from '@/lib/api';
import { Order } from '@/types';
import Header from '@/components/layout/Header';
import Footer from '@/components/layout/Footer';
import Image from 'next/image';
import { useAuth } from '@/context/AuthContext';
import Link from 'next/link';
import { useSettings } from '@/context/SettingsContext';

interface OrderDetailsClientProps {
  id: string;
}

const OrderDetailsClient: React.FC<OrderDetailsClientProps> = ({ id }) => {
  const router = useRouter();
  const [order, setOrder] = useState<Order | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [ratingOpen, setRatingOpen] = useState(false);
  const [currentItem, setCurrentItem] = useState<any | null>(null);
  const [rating, setRating] = useState<number>(0);
  const [comment, setComment] = useState<string>('');
  const [submitting, setSubmitting] = useState(false);
  const [ratingError, setRatingError] = useState<string | null>(null);
  const { user } = useAuth();
  const [myReviews, setMyReviews] = useState<
    Record<number, { id: number; rating: number; comment?: string }>
  >({});
  const { currency, locale, formatMoney } = useSettings();

  useEffect(() => {
    const fetchOrderDetails = async () => {
      try {
        setLoading(true);
        const response = await api.getOrderById(id as string);
        if (response.status === 'success') {
          setOrder(response.data);
        } else {
          setError('Order not found');
        }
      } catch (err) {
        console.error('Error fetching order:', err);
        setError('Failed to load order details');
      } finally {
        setLoading(false);
      }
    };

    if (id) {
      fetchOrderDetails();
    }
  }, [id]);

  useEffect(() => {
    const fetchMy = async () => {
      if (!id) return;
      try {
        const res = await api.getMyReviews(id as string);
        if ((res as any).data && Array.isArray((res as any).data)) {
          const map: Record<number, { id: number; rating: number; comment?: string }> = {};
          (res as any).data.forEach((r: any) => {
            map[r.order_item_id] = { id: r.id, rating: r.rating, comment: r.comment };
          });
          setMyReviews(map);
        }
      } catch {}
    };
    fetchMy();
  }, [id]);

  const canRate = (status: string) => {
    const s = status?.toLowerCase() || '';
    return s === 'delivered' || s === 'completed';
  };

  const openRateModal = (item: any) => {
    setCurrentItem(item);
    const itemId = item.id;
    const existing = itemId != null ? myReviews[itemId] : undefined;
    setRating(existing?.rating || 0);
    setComment(existing?.comment || '');
    setRatingError(null);
    setRatingOpen(true);
  };

  const submitReview = async () => {
    if (!user) {
      setRatingError('Please login to rate products');
      return;
    }
    if (!currentItem) return;
    if (rating < 1) {
      setRatingError('Please select a rating');
      return;
    }
    const itemId = currentItem.id;
    if (itemId == null) {
      setRatingError('Invalid order item');
      return;
    }
    setSubmitting(true);
    setRatingError(null);
    try {
      const existing = myReviews[itemId];
      if (existing) {
        const res = await api.updateReview(existing.id, {
          rating,
          comment: comment?.trim() || undefined,
        });
        setMyReviews((prev) => ({
          ...prev,
          [itemId]: { id: existing.id, rating, comment: comment?.trim() || undefined },
        }));
      } else {
        const res = await api.createReview({
          product_id: currentItem.product?.id || currentItem.product_id,
          order_item_id: itemId,
          rating,
          comment: comment?.trim() || undefined,
        });
        const newId = (res as any)?.data?.id;
        if (newId) {
          setMyReviews((prev) => ({
            ...prev,
            [itemId]: { id: newId, rating, comment: comment?.trim() || undefined },
          }));
        }
      }
      setRatingOpen(false);
    } catch (e: any) {
      setRatingError(e?.message || 'Failed to submit review');
    } finally {
      setSubmitting(false);
    }
  };

  const getStatusColor = (status: string) => {
    switch (status.toLowerCase()) {
      case 'pending':
        return 'bg-amber-100 text-amber-700 border-amber-200';
      case 'processing':
        return 'bg-blue-100 text-blue-700 border-blue-200';
      case 'shipped':
        return 'bg-purple-100 text-purple-700 border-purple-200';
      case 'delivered':
        return 'bg-emerald-100 text-emerald-700 border-emerald-200';
      case 'cancelled':
        return 'bg-rose-100 text-rose-700 border-rose-200';
      default:
        return 'bg-zinc-100 text-zinc-700 border-zinc-200';
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status.toLowerCase()) {
      case 'pending':
        return <Clock className="w-4 h-4" />;
      case 'processing':
        return <Package className="w-4 h-4" />;
      case 'shipped':
        return <Truck className="w-4 h-4" />;
      case 'delivered':
        return <CheckCircle2 className="w-4 h-4" />;
      case 'cancelled':
        return <AlertCircle className="w-4 h-4" />;
      default:
        return <Package className="w-4 h-4" />;
    }
  };

  const trackingSteps = [
    { key: 'pending', label: 'Order Placed', icon: Clock },
    { key: 'processing', label: 'Processing', icon: Package },
    { key: 'shipped', label: 'On the Way', icon: Truck },
    { key: 'delivered', label: 'Delivered', icon: CheckCircle2 },
  ];

  const currentStatusIndex = trackingSteps.findIndex(
    (step) => step.key === (order?.status || '').toLowerCase(),
  );

  if (loading) {
    return (
      <div className="min-h-screen bg-zinc-50">
        <Header />
        <div className="flex items-center justify-center h-[60vh]">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-emerald-500"></div>
        </div>
        <Footer />
      </div>
    );
  }

  if (error || !order) {
    return (
      <div className="min-h-screen bg-zinc-50">
        <Header />
        <div className="flex flex-col items-center justify-center h-[60vh] px-4 text-center">
          <div className="w-16 h-16 bg-rose-100 rounded-full flex items-center justify-center mb-4">
            <AlertCircle className="w-8 h-8 text-rose-600" />
          </div>
          <h1 className="text-2xl font-bold text-zinc-900 mb-2">
            {error || 'We could not find any order with this ID.'}
          </h1>
          <p className="text-sm text-zinc-500 mb-6 font-medium max-w-md">
            Please make sure you entered the correct Order ID. If you recently
            placed an order, it may take a moment before it appears here.
          </p>
          <button
            onClick={() => router.push('/order-tracking')}
            className="text-emerald-600 font-medium hover:underline flex items-center gap-1 text-sm"
          >
            <ChevronLeft className="w-4 h-4" /> Back to Order Tracking
          </button>
        </div>
        <Footer />
      </div>
    );
  }

  const safeStatus = order.status || '';

  return (
    <div className="min-h-screen bg-zinc-50">
      <Header />

      <main className="max-w-5xl mx-auto px-4 py-12">
        <div className="mb-8">
          <button
            onClick={() => router.push('/orders')}
            className="flex items-center gap-1 text-zinc-500 hover:text-emerald-600 transition-colors mb-4 group"
          >
            <ChevronLeft className="w-4 h-4 transition-transform group-hover:-translate-x-1" />
            <span>Back to Orders</span>
          </button>

          <div className="flex flex-col md:flex-row md:items-end justify-between gap-4">
            <div>
              <h1 className="text-3xl font-black text-zinc-900 mb-2">
                Order #{order.order_number || order.id}
              </h1>
              <div className="flex flex-wrap items-center gap-4 text-sm text-zinc-500">
                <span className="flex items-center gap-1.5">
                  <Calendar className="w-4 h-4" />
                  {new Date(order.created_at || '').toLocaleDateString(locale, {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric',
                  })}
                </span>
                <span
                  className={`px-3 py-1 rounded-full border text-xs font-bold uppercase tracking-wider flex items-center gap-1.5 ${getStatusColor(
                    safeStatus,
                  )}`}
                >
                  {getStatusIcon(safeStatus)}
                  {safeStatus}
                </span>
              </div>
            </div>

            <div className="text-right">
              <p className="text-sm text-zinc-500 mb-1">Total Amount</p>
              <p className="text-3xl font-black text-emerald-600">
                {formatMoney(Number(order.total))}
              </p>
            </div>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          <div className="lg:col-span-2 space-y-6">
            <section className="bg-white rounded-3xl shadow-sm border border-zinc-100 overflow-hidden">
              <div className="p-6 border-b border-zinc-100 flex items-center justify-between">
                <div>
                  <p className="text-[11px] font-black text-zinc-400 uppercase tracking-[0.25em] mb-1">
                    Order Status
                  </p>
                  <p className="text-sm text-zinc-500">
                    Track your order&apos;s journey from our store to your doorstep.
                  </p>
                </div>
                <div className="hidden md:flex items-center gap-2 text-xs text-zinc-500">
                  <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
                  Live status
                </div>
              </div>

              <div className="p-6">
                <div className="flex flex-col md:flex-row items-center gap-6">
                  <div className="flex-1 space-y-4">
                    {trackingSteps.map((step, index) => {
                      const isCompleted = index <= currentStatusIndex;
                      const isCurrent = index === currentStatusIndex;

                      return (
                        <div key={step.key} className="flex items-center gap-4">
                          <div
                            className={`w-10 h-10 rounded-2xl flex items-center justify-center border-2 ${
                              isCompleted
                                ? 'border-emerald-500 bg-emerald-50 text-emerald-600'
                                : 'border-zinc-200 bg-zinc-50 text-zinc-400'
                            }`}
                          >
                            <step.icon className="w-5 h-5" />
                          </div>
                          <div className="flex-1">
                            <p className="text-sm font-semibold text-zinc-900">
                              {step.label}
                            </p>
                            <p className="text-xs text-zinc-500">
                              {isCurrent
                                ? 'This is the current status of your order.'
                                : isCompleted
                                ? 'This step has been completed.'
                                : 'This step is pending.'}
                            </p>
                          </div>
                          <div className="hidden md:block w-24">
                            {isCurrent && (
                              <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full bg-emerald-50 text-emerald-700 text-[10px] font-bold uppercase tracking-widest">
                                <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse" />
                                Current
                              </span>
                            )}
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              </div>
            </section>

            <section className="bg-white rounded-3xl shadow-sm border border-zinc-100 overflow-hidden">
              <div className="p-8 border-b border-zinc-100">
                <h2 className="text-xl font-bold text-zinc-900">Items Ordered</h2>
              </div>
              <div className="divide-y divide-zinc-100">
                {order.items.map((item, idx) => {
                  const canItemRate = canRate(order.status || '');
                  const existing = item.id != null ? myReviews[item.id] : undefined;

                  return (
                    <div key={idx} className="p-6 flex flex-col md:flex-row gap-4">
                      <div className="flex-1 flex gap-4">
                        <div className="w-16 h-16 rounded-2xl bg-zinc-50 flex items-center justify-center overflow-hidden border border-zinc-100">
                          <Image
                            src={getImageUrl(item.product?.image || item.product?.imageUrl)}
                            alt={item.product?.name || 'Product'}
                            width={64}
                            height={64}
                            className="w-full h-full object-contain"
                          />
                        </div>
                        <div>
                          <p className="font-semibold text-zinc-900">
                            {item.product?.name || `Product ID: ${item.product_id}`}
                          </p>
                          <p className="text-xs text-zinc-500">
                            Qty: {item.quantity} ×{' '}
                            {formatMoney(Number(item.price || 0))}
                          </p>
                          <p className="text-xs text-zinc-500">
                            Subtotal: {formatMoney(Number(item.quantity || 0) * Number(item.price || 0))}
                          </p>
                        </div>
                      </div>

                      <div className="flex flex-col items-end gap-2">
                        <p className="text-sm font-semibold text-zinc-900">
                          {formatMoney(Number(item.quantity || 0) * Number(item.price || 0))}
                        </p>
                        {canItemRate && (
                          <button
                            onClick={() => openRateModal(item)}
                            className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full border border-emerald-200 text-emerald-700 text-[11px] font-bold uppercase tracking-[0.18em] hover:bg-emerald-50"
                          >
                            <Star className="w-3.5 h-3.5" />
                            {existing ? 'Update Rating' : 'Rate Item'}
                          </button>
                        )}
                        {existing && (
                          <p className="text-[11px] text-zinc-400">
                            Your rating: {existing.rating}★
                          </p>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            </section>
          </div>

          <div className="space-y-6">
            <section className="bg-white rounded-3xl shadow-sm border border-zinc-100 p-6 space-y-4">
              <div className="flex items-center gap-3 mb-2">
                <div className="w-10 h-10 rounded-2xl bg-emerald-50 flex items-center justify-center text-emerald-600">
                  <MapPin className="w-5 h-5" />
                </div>
                <div>
                  <p className="text-[11px] font-black text-zinc-400 uppercase tracking-[0.25em]">
                    Shipping Address
                  </p>
                  <p className="text-sm text-zinc-500">
                    Where your order will be delivered.
                  </p>
                </div>
              </div>
              <div className="space-y-1 text-sm text-zinc-600">
                <p className="font-semibold text-zinc-900">
                  {order.shipping_address.first_name} {order.shipping_address.last_name}
                </p>
                <p>{order.shipping_address.address}</p>
                <p>
                  {order.shipping_address.city}, {order.shipping_address.zip}
                </p>
                <p className="text-zinc-500 text-xs">
                  Phone: {order.shipping_address.phone}
                </p>
              </div>
            </section>

            <section className="bg-white rounded-3xl shadow-sm border border-zinc-100 p-6 space-y-4">
              <div className="flex items-center gap-3 mb-2">
                <div className="w-10 h-10 rounded-2xl bg-zinc-900 flex items-center justify-center text-white">
                  <CreditCard className="w-5 h-5" />
                </div>
                <div>
                  <p className="text-[11px] font-black text-zinc-400 uppercase tracking-[0.25em]">
                    Payment
                  </p>
                  <p className="text-sm text-zinc-500">
                    Summary of how you paid for this order.
                  </p>
                </div>
              </div>
              <div className="space-y-2 text-sm text-zinc-600">
                <div className="flex items-center justify-between">
                  <span>Payment Status</span>
                  <span
                    className={`px-2.5 py-1 rounded-full text-[11px] font-bold uppercase tracking-[0.18em] ${
                      (order.payment_status || '').toLowerCase() === 'paid'
                        ? 'bg-emerald-50 text-emerald-700'
                        : 'bg-amber-50 text-amber-700'
                    }`}
                  >
                    {order.payment_status || 'Pending'}
                  </span>
                </div>
                <div className="flex items-center justify-between">
                  <span>Transaction ID</span>
                  <span className="font-mono text-xs text-zinc-500">
                    {order.transaction_id || 'N/A'}
                  </span>
                </div>
              </div>
            </section>

            <section className="bg-white rounded-3xl shadow-sm border border-zinc-100 p-6 space-y-4">
              <div className="flex items-center gap-3 mb-2">
                <div className="w-10 h-10 rounded-2xl bg-zinc-50 flex items-center justify-center text-zinc-700">
                  <Package className="w-5 h-5" />
                </div>
                <div>
                  <p className="text-[11px] font-black text-zinc-400 uppercase tracking-[0.25em]">
                    Order Summary
                  </p>
                  <p className="text-sm text-zinc-500">
                    Detailed breakdown of your order charges.
                  </p>
                </div>
              </div>
              <div className="space-y-2 text-sm text-zinc-600">
                <div className="flex items-center justify-between">
                  <span>Subtotal</span>
                  <span>{formatMoney(Number(order.subtotal || 0))}</span>
                </div>
                <div className="flex items-center justify-between">
                  <span>Delivery Fee</span>
                  <span>{formatMoney(Number(order.delivery_fee || 0))}</span>
                </div>
                <div className="flex items-center justify-between">
                  <span>Tax</span>
                  <span>{formatMoney(Number(order.tax || 0))}</span>
                </div>
                {order.discount_amount ? (
                  <div className="flex items-center justify-between text-emerald-600">
                    <span>Discount</span>
                    <span>-{formatMoney(Number(order.discount_amount || 0))}</span>
                  </div>
                ) : null}
                <div className="pt-2 border-t border-zinc-100 flex items-center justify-between font-semibold">
                  <span>Total</span>
                  <span>{formatMoney(Number(order.total || 0))}</span>
                </div>
              </div>
            </section>

            <section className="bg-emerald-50 rounded-3xl border border-emerald-100 p-6 space-y-3">
              <h3 className="text-sm font-semibold text-emerald-900">
                Need help with this order?
              </h3>
              <p className="text-xs text-emerald-800">
                If something doesn&apos;t look right or you have a question, our support team is
                here to help.
              </p>
              <button
                onClick={() => {
                  if (order.id != null) {
                    router.push(`/support?order_id=${order.id}`);
                  } else {
                    router.push('/support');
                  }
                }}
                className="w-full py-4 bg-white text-emerald-600 rounded-2xl font-black text-sm transition-transform active:scale-95"
              >
                Contact Support
              </button>
            </section>
          </div>
        </div>
      </main>

      {ratingOpen && currentItem && (
        <div className="fixed inset-0 bg-black/30 flex items-center justify-center z-50">
          <div className="bg-white rounded-2xl p-6 w-full max-w-md border border-zinc-100">
            <h3 className="text-lg font-bold text-zinc-900 mb-4">
              Rate {currentItem.product?.name || 'Product'}
            </h3>
            <div className="flex items-center gap-2 mb-4">
              {[1, 2, 3, 4, 5].map((i) => (
                <button
                  key={i}
                  onClick={() => setRating(i)}
                  className={`w-10 h-10 rounded-xl border flex items-center justify-center transition-colors ${
                    i <= rating
                      ? 'bg-emerald-600 text-white border-emerald-600'
                      : 'bg-white text-zinc-400 border-zinc-200'
                  }`}
                >
                  <Star size={16} />
                </button>
              ))}
            </div>
            <textarea
              value={comment}
              onChange={(e) => setComment(e.target.value)}
              placeholder="Share your thoughts (optional)"
              className="w-full border border-zinc-200 rounded-xl p-3 text-sm mb-3 outline-none focus:border-emerald-600"
              rows={4}
            />
            {ratingError && (
              <p className="text-xs text-rose-600 mb-2">{ratingError}</p>
            )}
            <div className="flex items-center justify-end gap-3 mt-2">
              <button
                onClick={() => setRatingOpen(false)}
                className="px-4 py-2 text-sm font-medium text-zinc-500 hover:text-zinc-700"
              >
                Cancel
              </button>
              <button
                onClick={submitReview}
                disabled={submitting}
                className="px-5 py-2 rounded-xl bg-emerald-600 text-white text-sm font-bold disabled:opacity-60 flex items-center gap-2"
              >
                {submitting && <Loader2 className="w-4 h-4 animate-spin" />}
                Submit Rating
              </button>
            </div>
          </div>
        </div>
      )}

      <Footer />
    </div>
  );
};

export default OrderDetailsClient;
