'use client';

import { useEffect, useMemo, useState } from 'react';
import Link from 'next/link';
import { useParams, useRouter } from 'next/navigation';
import Image from 'next/image';
import { ArrowLeft, Loader2, RefreshCw, Save, Truck } from 'lucide-react';
import toast from 'react-hot-toast';
import { fetchOrderById, updateOrderStatus } from '@/lib/services/orders';
import type { FrontendOrder } from '@/lib/types';

const statusOptions = [
  { value: 'pending', label: 'Pending' },
  { value: 'processing', label: 'Processing' },
  { value: 'shipped', label: 'Shipped' },
  { value: 'delivered', label: 'Delivered' },
  { value: 'completed', label: 'Completed' },
  { value: 'cancelled', label: 'Cancelled' },
];

const statusColors: Record<string, string> = {
  pending: 'bg-yellow-100 text-yellow-800',
  processing: 'bg-blue-100 text-blue-800',
  shipped: 'bg-purple-100 text-purple-800',
  delivered: 'bg-emerald-100 text-emerald-700',
  completed: 'bg-green-100 text-green-800',
  cancelled: 'bg-red-100 text-red-700',
};

const formatCurrency = (amount: number, currency: string) => {
  try {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency,
      maximumFractionDigits: currency === 'PKR' ? 0 : 2,
    }).format(amount);
  } catch {
    return `${currency} ${amount.toFixed(2)}`;
  }
};

export default function AdminOrderDetailPage() {
  const params = useParams<{ id: string }>();
  const router = useRouter();
  const [order, setOrder] = useState<FrontendOrder | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [selectedStatus, setSelectedStatus] = useState<string>('');
  const [isSaving, setIsSaving] = useState(false);

  const orderId = params?.id;

  const loadOrder = async () => {
    if (!orderId) {
      setError('Order ID missing from URL.');
      setIsLoading(false);
      return;
    }

    try {
      setError(null);
      const data = await fetchOrderById(orderId);
      if (!data) {
        setError('Order not found.');
        setOrder(null);
        return;
      }
      setOrder(data);
      setSelectedStatus(data.status);
    } catch (err) {
      console.error(err);
      setError('Unable to load order. Please try again.');
    } finally {
      setIsLoading(false);
      setIsRefreshing(false);
    }
  };

  useEffect(() => {
    setIsLoading(true);
    void loadOrder();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [orderId]);

  const handleStatusSave = async () => {
    if (!order || !selectedStatus || selectedStatus === order.status) {
      toast.error('Select a different status to update.');
      return;
    }

    try {
      setIsSaving(true);
      const updated = await updateOrderStatus(order.id, selectedStatus);
      setOrder(updated);
      toast.success('Order status updated.');
    } catch (err) {
      console.error(err);
      toast.error('Failed to update status. Please try again.');
    } finally {
      setIsSaving(false);
    }
  };

  const orderSummary = useMemo(() => {
    if (!order) return null;

    const totalQuantity = order.items.reduce((sum, item) => sum + item.quantity, 0);
    const subtotalFromItems = order.items.reduce((sum, item) => {
      const lineTotal = Number.isFinite(item.subtotal) ? item.subtotal : item.price * item.quantity;
      return sum + lineTotal;
    }, 0);
    const shipping = Number.isFinite(order.shipping) ? order.shipping : 0;
    const tax = Number.isFinite(order.tax) ? order.tax : 0;
    const total = subtotalFromItems + shipping + tax;

    return {
      totalQuantity,
      rows: [
        {
          label: `Subtotal (${totalQuantity} ${totalQuantity === 1 ? 'item' : 'items'})`,
          value: subtotalFromItems,
        },
        { label: 'Shipping', value: shipping },
        { label: 'Tax', value: tax },
        { label: 'Total', value: total, highlight: true },
      ],
    };
  }, [order]);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-full min-h-[50vh]">
        <Loader2 className="w-8 h-8 animate-spin text-gray-500" />
      </div>
    );
  }

  if (error || !order) {
    return (
      <div className="space-y-6">
        <div className="flex items-center gap-2">
          <Link
            href="/admin/orders"
            className="inline-flex items-center gap-2 text-sm font-medium text-gray-600 hover:text-gray-900"
          >
            <ArrowLeft className="w-4 h-4" />
            Back to orders
          </Link>
        </div>
        <div className="bg-red-50 border border-red-200 text-red-700 px-8 py-6 rounded-lg">
          {error ?? 'Order not found.'}
        </div>
      </div>
    );
  }

  const shipping = order.raw;
  const statusBadgeClass = statusColors[order.status.toLowerCase()] ?? 'bg-gray-100 text-gray-800';

  return (
    <div className="space-y-8">
      <div className="flex items-center justify-between">
        <div className="space-y-2">
          <Link
            href="/admin/orders"
            className="inline-flex items-center gap-2 text-sm font-medium text-gray-600 hover:text-gray-900"
          >
            <ArrowLeft className="w-4 h-4" />
            Back to orders
          </Link>
          <h1 className="text-3xl font-bold text-gray-900">{order.orderNumber}</h1>
          <div className="flex items-center gap-3 text-sm text-gray-600">
            <span className={`px-2 py-1 rounded-full text-xs font-semibold ${statusBadgeClass}`}>
              {order.status}
            </span>
            <span>
              Placed on{' '}
              {order.createdAt
                ? order.createdAt.toLocaleString()
                : shipping.createdAt
                ? new Date(shipping.createdAt).toLocaleString()
                : 'Unknown'}
            </span>
            {isRefreshing && <Loader2 className="w-4 h-4 animate-spin text-gray-400" />}
          </div>
        </div>
        <div className="flex items-center gap-3">
          <button
            onClick={() => {
              setIsRefreshing(true);
              void loadOrder();
            }}
            className="inline-flex items-center gap-2 px-3 py-2 rounded-lg border border-gray-300 text-sm font-medium text-gray-700 hover:bg-gray-100 transition-colors"
          >
            <RefreshCw className="w-4 h-4" />
            Refresh
          </button>
          <div className="flex items-center gap-2 border border-gray-300 rounded-lg px-3 py-2 bg-white">
            <select
              value={selectedStatus}
              onChange={(e) => setSelectedStatus(e.target.value)}
              className="bg-transparent focus:outline-none text-sm font-medium text-gray-900"
            >
              {statusOptions.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
            <button
              onClick={handleStatusSave}
              disabled={isSaving || selectedStatus === order.status}
              className="inline-flex items-center gap-2 px-3 py-1.5 rounded-md bg-gray-900 text-white text-xs font-semibold uppercase tracking-wide hover:bg-gray-800 disabled:opacity-70 disabled:cursor-not-allowed"
            >
              {isSaving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
              {isSaving ? 'Saving' : 'Save'}
            </button>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
        {/* Order Items */}
        <div className="xl:col-span-2 bg-white border border-gray-200 rounded-lg shadow-sm">
          <div className="border-b border-gray-200 px-6 py-4 flex items-center gap-2">
            <Truck className="w-4 h-4 text-gray-500" />
            <h2 className="text-lg font-semibold text-gray-900">Items</h2>
          </div>
          <div className="divide-y divide-gray-200">
            {order.items.map((item) => (
              <div key={item.id} className="px-6 py-4 flex gap-4">
                <div className="relative w-20 h-24 rounded bg-gray-100 overflow-hidden">
                  {item.productImage ? (
                    <Image
                      src={item.productImage}
                      alt={item.name}
                      fill
                      className="object-cover"
                      sizes="160px"
                      unoptimized
                    />
                  ) : (
                    <div className="flex items-center justify-center w-full h-full text-xs text-gray-500">
                      No image
                    </div>
                  )}
                </div>
                <div className="flex-1 min-w-0 space-y-2">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm font-semibold text-gray-900">{item.name}</p>
                      <p className="text-xs text-gray-500">Qty: {item.quantity}</p>
                    </div>
              <div className="text-right space-y-1">
                <div className="text-xs text-gray-500">
                  {formatCurrency(item.price, order.currency)} each
                </div>
                <div className="text-sm font-semibold text-gray-900">
                  {formatCurrency(item.price * item.quantity, order.currency)}
                </div>
              </div>
                  </div>
                  <div className="grid grid-cols-2 md:grid-cols-3 gap-1 text-xs text-gray-600">
                    {item.attributes.size && <span>Size: {item.attributes.size}</span>}
                    {item.attributes.fabric && <span>Fabric: {item.attributes.fabric}</span>}
                    {item.attributes.dupatta && <span>Dupatta: {item.attributes.dupatta}</span>}
                    {item.attributes.trousers && <span>Trousers: {item.attributes.trousers}</span>}
                    {item.attributes.silkScarf && <span>Silk Scarf: Yes</span>}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Summary */}
        <div className="space-y-6">
          <div className="bg-white border border-gray-200 rounded-lg shadow-sm">
            <div className="border-b border-gray-200 px-6 py-4">
              <h2 className="text-lg font-semibold text-gray-900">Order Summary</h2>
            </div>
            <div className="px-6 py-4 space-y-3 text-sm text-gray-700">
              {orderSummary?.rows.map((row) => (
                <div
                  key={row.label}
                  className={`flex items-center justify-between ${row.highlight ? 'font-semibold text-gray-900 border-t border-gray-200 pt-3 mt-3' : ''
                    }`}
                >
                  <span>{row.label}</span>
                  <span>{formatCurrency(row.value, order.currency)}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="bg-white border border-gray-200 rounded-lg shadow-sm">
            <div className="border-b border-gray-200 px-6 py-4">
              <h2 className="text-lg font-semibold text-gray-900">Customer</h2>
            </div>
            <div className="px-6 py-4 space-y-2 text-sm text-gray-700">
              <div>
                <span className="block text-xs uppercase text-gray-500">Name</span>
                <span>{order.customerName || 'Guest'}</span>
              </div>
              {order.customerEmail && (
                <div>
                  <span className="block text-xs uppercase text-gray-500">Email</span>
                  <span>{order.customerEmail}</span>
                </div>
              )}
              {order.customerPhone && (
                <div>
                  <span className="block text-xs uppercase text-gray-500">Phone</span>
                  <span>{order.customerPhone}</span>
                </div>
              )}
            </div>
          </div>

          <div className="bg-white border border-gray-200 rounded-lg shadow-sm">
            <div className="border-b border-gray-200 px-6 py-4">
              <h2 className="text-lg font-semibold text-gray-900">Shipping Address</h2>
            </div>
            <div className="px-6 py-4 space-y-2 text-sm text-gray-700">
              <div>
                <span className="block text-xs uppercase text-gray-500">Recipient</span>
                <span>
                  {shipping.shippingFirstName} {shipping.shippingLastName}
                </span>
              </div>
              <div>
                <span className="block text-xs uppercase text-gray-500">Address</span>
                <span>
                  {shipping.shippingAddressLine1}
                  {shipping.shippingAddressLine2 ? `, ${shipping.shippingAddressLine2}` : ''}
                </span>
              </div>
              <div>
                <span className="block text-xs uppercase text-gray-500">City / State</span>
                <span>
                  {shipping.shippingCity}
                  {shipping.shippingState ? `, ${shipping.shippingState}` : ''}
                </span>
              </div>
              <div>
                <span className="block text-xs uppercase text-gray-500">Postal Code</span>
                <span>{shipping.shippingPostalCode}</span>
              </div>
              <div>
                <span className="block text-xs uppercase text-gray-500">Country</span>
                <span>{shipping.shippingCountry}</span>
              </div>
              <div>
                <span className="block text-xs uppercase text-gray-500">Contact</span>
                <span>{shipping.shippingPhone}</span>
              </div>
            </div>
          </div>

          {(shipping.notes || shipping.heightFeet || shipping.heightInch) && (
            <div className="bg-white border border-gray-200 rounded-lg shadow-sm">
              <div className="border-b border-gray-200 px-6 py-4">
                <h2 className="text-lg font-semibold text-gray-900">Additional Information</h2>
              </div>
              <div className="px-6 py-4 space-y-2 text-sm text-gray-700">
                {shipping.heightFeet && (
                  <div>
                    <span className="block text-xs uppercase text-gray-500">Height</span>
                    <span>
                      {shipping.heightFeet} ft {shipping.heightInch ? `${shipping.heightInch} in` : ''}
                    </span>
                  </div>
                )}
                {shipping.notes && (
                  <div>
                    <span className="block text-xs uppercase text-gray-500">Notes</span>
                    <span>{shipping.notes}</span>
                  </div>
                )}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

