'use client';

import { useState, useEffect, use } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import SidebarLayout from '../../../components/sidebar-layout';
import { useFormatCurrency } from '../../../hooks/useFormatCurrency';
import { 
  ArrowLeft, 
  Glasses, 
  User, 
  Calendar,
  DollarSign,
  Truck,
  CheckCircle,
  Clock,
  Package,
  Edit,
  Trash2,
  XCircle
} from 'lucide-react';

interface Order {
  _id: string;
  orderNumber: string;
  patientId: {
    _id: string;
    name: string;
    patientId: string;
    phone?: string;
    email?: string;
  };
  prescriptionId?: {
    _id: string;
    prescriptionNumber: string;
    type: string;
  };
  orderDate: string;
  orderType: string;
  spectacleOrder?: {
    frameDetails?: {
      brand: string;
      model: string;
      color: string;
      size: string;
      price: number;
    };
    lensOD?: {
      type: string;
      material: string;
      coatings: string[];
      tint: string;
      price: number;
    };
    lensOS?: {
      type: string;
      material: string;
      coatings: string[];
      price: number;
    };
    labInstructions?: string;
  };
  pricing: {
    framePrice: number;
    lensPrice: number;
    discount: number;
    discountType: string;
    total: number;
  };
  payment: {
    method: string;
    amountPaid: number;
    balance: number;
  };
  status: string;
  delivery: {
    method: string;
    address?: string;
  };
  timeline: {
    ordered?: string;
    sentToLab?: string;
    labCompleted?: string;
    readyForPickup?: string;
    delivered?: string;
  };
  notes?: string;
  createdAt: string;
}

export default function OrderDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const router = useRouter();
  const formatCurrency = useFormatCurrency();
  const [order, setOrder] = useState<Order | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [updating, setUpdating] = useState(false);

  useEffect(() => {
    fetchOrder();
  }, [id]);

  const fetchOrder = async () => {
    try {
      const response = await fetch(`/api/optical-shop/orders/${id}`);
      if (response.ok) {
        const data = await response.json();
        setOrder(data);
      } else {
        setError('Order not found');
      }
    } catch (err) {
      console.error('Error fetching order:', err);
      setError('Failed to load order');
    } finally {
      setLoading(false);
    }
  };

  const handleStatusUpdate = async (newStatus: string) => {
    if (!order) return;
    setUpdating(true);
    try {
      const response = await fetch(`/api/optical-shop/orders/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: newStatus })
      });
      if (response.ok) {
        fetchOrder();
      }
    } catch (err) {
      console.error('Error updating status:', err);
    } finally {
      setUpdating(false);
    }
  };

  const handleDelete = async () => {
    if (!confirm('Are you sure you want to delete this order?')) return;
    try {
      const response = await fetch(`/api/optical-shop/orders/${id}`, { method: 'DELETE' });
      if (response.ok) {
        router.push('/optical-shop');
      }
    } catch (err) {
      console.error('Error deleting order:', err);
    }
  };

  const getStatusBadge = (status: string) => {
    const styles: Record<string, string> = {
      ordered: 'bg-blue-100 text-blue-800',
      inProduction: 'bg-yellow-100 text-yellow-800',
      qualityCheck: 'bg-purple-100 text-purple-800',
      ready: 'bg-green-100 text-green-800',
      dispatched: 'bg-indigo-100 text-indigo-800',
      delivered: 'bg-emerald-100 text-emerald-800',
      cancelled: 'bg-red-100 text-red-800'
    };
    const labels: Record<string, string> = {
      ordered: 'Ordered',
      inProduction: 'In Production',
      qualityCheck: 'Quality Check',
      ready: 'Ready for Pickup',
      dispatched: 'Dispatched',
      delivered: 'Delivered',
      cancelled: 'Cancelled'
    };
    return (
      <span className={`px-3 py-1 rounded-full text-sm font-medium ${styles[status] || 'bg-gray-100 text-gray-800'}`}>
        {labels[status] || status}
      </span>
    );
  };

  const statusFlow = ['ordered', 'inProduction', 'qualityCheck', 'ready', 'delivered'];
  const currentStatusIndex = order ? statusFlow.indexOf(order.status) : 0;

  if (loading) {
    return (
      <SidebarLayout title="Order Details" description="Loading...">
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-teal-600"></div>
        </div>
      </SidebarLayout>
    );
  }

  if (error || !order) {
    return (
      <SidebarLayout title="Order Details" description="Error">
        <div className="max-w-4xl mx-auto">
          <Link href="/optical-shop" className="inline-flex items-center gap-2 text-gray-600 hover:text-gray-900 mb-6">
            <ArrowLeft className="h-4 w-4" />
            Back to Optical Shop
          </Link>
          <div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
            <XCircle className="h-12 w-12 text-red-500 mx-auto mb-4" />
            <h2 className="text-lg font-semibold text-red-800">{error || 'Order not found'}</h2>
          </div>
        </div>
      </SidebarLayout>
    );
  }

  return (
    <SidebarLayout title="Order Details" description={`Order #${order.orderNumber}`}>
      <div className="max-w-4xl mx-auto">
        <div className="mb-6 flex items-center justify-between">
          <Link href="/optical-shop" className="inline-flex items-center gap-2 text-gray-600 hover:text-gray-900">
            <ArrowLeft className="h-4 w-4" />
            Back to Optical Shop
          </Link>
          <div className="flex gap-2">
            <button
              onClick={handleDelete}
              className="inline-flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700"
            >
              <Trash2 className="h-4 w-4" />
              Delete
            </button>
          </div>
        </div>

        {/* Header */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6 mb-6">
          <div className="flex items-start justify-between mb-4">
            <div>
              <h1 className="text-2xl font-bold text-gray-900 flex items-center gap-2">
                <Glasses className="h-6 w-6 text-teal-600" />
                Order #{order.orderNumber}
              </h1>
              <p className="text-gray-500 mt-1 capitalize">{order.orderType} Order</p>
            </div>
            {getStatusBadge(order.status)}
          </div>

          <div className="grid grid-cols-3 gap-4 mt-6">
            <div className="flex items-center gap-3">
              <Calendar className="h-5 w-5 text-gray-400" />
              <div>
                <p className="text-xs text-gray-500">Order Date</p>
                <p className="font-medium">{new Date(order.orderDate).toLocaleDateString()}</p>
              </div>
            </div>
            <div className="flex items-center gap-3">
              <DollarSign className="h-5 w-5 text-gray-400" />
              <div>
                <p className="text-xs text-gray-500">Total</p>
                <p className="font-medium">{formatCurrency(order.pricing.total)}</p>
              </div>
            </div>
            <div className="flex items-center gap-3">
              <Truck className="h-5 w-5 text-gray-400" />
              <div>
                <p className="text-xs text-gray-500">Delivery</p>
                <p className="font-medium capitalize">{order.delivery.method}</p>
              </div>
            </div>
          </div>
        </div>

        {/* Status Timeline */}
        {order.status !== 'cancelled' && (
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6 mb-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4">Order Progress</h2>
            <div className="flex items-center justify-between">
              {statusFlow.map((status, index) => (
                <div key={status} className="flex items-center">
                  <div className={`flex flex-col items-center ${index <= currentStatusIndex ? 'text-teal-600' : 'text-gray-300'}`}>
                    <div className={`w-10 h-10 rounded-full flex items-center justify-center ${
                      index <= currentStatusIndex ? 'bg-teal-100' : 'bg-gray-100'
                    }`}>
                      {index < currentStatusIndex ? (
                        <CheckCircle className="h-6 w-6" />
                      ) : index === currentStatusIndex ? (
                        <Clock className="h-6 w-6" />
                      ) : (
                        <div className="w-3 h-3 rounded-full bg-current" />
                      )}
                    </div>
                    <p className="text-xs mt-2 text-center capitalize">
                      {status === 'inProduction' ? 'Production' : status === 'qualityCheck' ? 'QC' : status}
                    </p>
                  </div>
                  {index < statusFlow.length - 1 && (
                    <div className={`w-16 h-1 mx-2 ${index < currentStatusIndex ? 'bg-teal-400' : 'bg-gray-200'}`} />
                  )}
                </div>
              ))}
            </div>

            {order.status !== 'delivered' && (
              <div className="mt-6 flex gap-2">
                {currentStatusIndex < statusFlow.length - 1 && (
                  <button
                    onClick={() => handleStatusUpdate(statusFlow[currentStatusIndex + 1])}
                    disabled={updating}
                    className="px-4 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 disabled:opacity-50"
                  >
                    {updating ? 'Updating...' : `Mark as ${statusFlow[currentStatusIndex + 1] === 'inProduction' ? 'In Production' : statusFlow[currentStatusIndex + 1]}`}
                  </button>
                )}
              </div>
            )}
          </div>
        )}

        {/* Patient Info */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
              <User className="h-5 w-5 text-teal-600" />
              Patient
            </h2>
            <div className="space-y-3">
              <div>
                <p className="text-sm text-gray-500">Name</p>
                <Link href={`/patients/${order.patientId._id}`} className="font-medium text-teal-600 hover:text-teal-700">
                  {order.patientId.name}
                </Link>
              </div>
              <div>
                <p className="text-sm text-gray-500">Patient ID</p>
                <p className="font-medium">{order.patientId.patientId}</p>
              </div>
              {order.patientId.phone && (
                <div>
                  <p className="text-sm text-gray-500">Phone</p>
                  <p className="font-medium">{order.patientId.phone}</p>
                </div>
              )}
            </div>
          </div>

          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
              <DollarSign className="h-5 w-5 text-teal-600" />
              Payment
            </h2>
            <div className="space-y-3">
              <div className="flex justify-between">
                <span className="text-gray-500">Frame</span>
                <span>{formatCurrency(order.pricing.framePrice)}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-500">Lenses</span>
                <span>{formatCurrency(order.pricing.lensPrice)}</span>
              </div>
              {order.pricing.discount > 0 && (
                <div className="flex justify-between text-red-600">
                  <span>Discount</span>
                  <span>-{formatCurrency(order.pricing.discount)}</span>
                </div>
              )}
              <div className="flex justify-between font-bold pt-2 border-t">
                <span>Total</span>
                <span>{formatCurrency(order.pricing.total)}</span>
              </div>
              <div className="flex justify-between text-green-600">
                <span>Paid</span>
                <span>{formatCurrency(order.payment.amountPaid)}</span>
              </div>
              {order.payment.balance > 0 && (
                <div className="flex justify-between text-orange-600 font-medium">
                  <span>Balance Due</span>
                  <span>{formatCurrency(order.payment.balance)}</span>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Spectacle Details */}
        {order.spectacleOrder && (
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6 mb-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
              <Glasses className="h-5 w-5 text-teal-600" />
              Spectacle Order Details
            </h2>
            
            {order.spectacleOrder.frameDetails && (
              <div className="mb-4 p-4 bg-gray-50 rounded-lg">
                <h3 className="font-medium text-gray-900 mb-2">Frame</h3>
                <p className="text-gray-700">
                  {order.spectacleOrder.frameDetails.brand} {order.spectacleOrder.frameDetails.model}
                </p>
                <p className="text-sm text-gray-500">
                  {order.spectacleOrder.frameDetails.color} | Size: {order.spectacleOrder.frameDetails.size}
                </p>
              </div>
            )}

            {order.spectacleOrder.lensOD && (
              <div className="grid grid-cols-2 gap-4">
                <div className="p-4 bg-gray-50 rounded-lg">
                  <h3 className="font-medium text-gray-900 mb-2">Lens Details</h3>
                  <p className="text-sm"><span className="text-gray-500">Type:</span> {order.spectacleOrder.lensOD.type}</p>
                  <p className="text-sm"><span className="text-gray-500">Material:</span> {order.spectacleOrder.lensOD.material}</p>
                  {order.spectacleOrder.lensOD.coatings?.length > 0 && (
                    <div className="mt-2">
                      <p className="text-sm text-gray-500">Coatings:</p>
                      <div className="flex flex-wrap gap-1 mt-1">
                        {order.spectacleOrder.lensOD.coatings.map((c, i) => (
                          <span key={i} className="px-2 py-0.5 bg-teal-100 text-teal-700 rounded text-xs">{c}</span>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
                
                {order.spectacleOrder.labInstructions && (
                  <div className="p-4 bg-gray-50 rounded-lg">
                    <h3 className="font-medium text-gray-900 mb-2">Lab Instructions</h3>
                    <p className="text-sm text-gray-700">{order.spectacleOrder.labInstructions}</p>
                  </div>
                )}
              </div>
            )}
          </div>
        )}

        {/* Notes */}
        {order.notes && (
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6 mb-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4">Notes</h2>
            <p className="text-gray-700">{order.notes}</p>
          </div>
        )}

        {/* Metadata */}
        <div className="text-sm text-gray-500 text-center">
          <p>Created: {new Date(order.createdAt).toLocaleString()}</p>
        </div>
      </div>
    </SidebarLayout>
  );
}
