"use client";

import React, { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { purchaseOrderService } from "../../../../services/api";
import { Supplier, PurchaseOrder } from "../../../../types/purchase-order";
import { formatDate } from "../../../../utils/dateUtils";

export default function SupplierDetailsPage({
  params,
}: {
  params: { id: string };
}) {
  const router = useRouter();
  const supplierId = params.id;
  const [supplier, setSupplier] = useState<Supplier | null>(null);
  const [purchaseOrders, setPurchaseOrders] = useState<PurchaseOrder[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchSupplierData = async () => {
      try {
        setLoading(true);
        const response = await purchaseOrderService.getSupplier(
          Number(supplierId)
        );
        setSupplier(response.data);

        // In a real application, we would fetch related purchase orders here
        // For now, we'll fetch all purchase orders and filter the ones for this supplier
        const poResponse = await purchaseOrderService.getAllPurchaseOrders();
        const filteredOrders = poResponse.data.filter(
          (order: PurchaseOrder) => order.supplierId === Number(supplierId)
        );
        setPurchaseOrders(filteredOrders);

        setError(null);
      } catch (err) {
        console.error("Failed to fetch supplier details:", err);
        setError("Failed to load supplier details. Please try again.");
      } finally {
        setLoading(false);
      }
    };

    fetchSupplierData();
  }, [supplierId]);

  if (loading) {
    return (
      <div className="flex justify-center items-center h-40">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mr-3"></div>
        <span>Loading supplier details...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-red-100 text-red-700 p-4 rounded-md">
        <p className="font-medium">Error</p>
        <p>{error}</p>
        <button
          onClick={() => router.push("/suppliers")}
          className="mt-4 bg-white text-red-700 py-2 px-4 rounded-md hover:bg-gray-100"
        >
          Back to Suppliers
        </button>
      </div>
    );
  }

  if (!supplier) {
    return (
      <div className="bg-yellow-100 text-yellow-700 p-4 rounded-md">
        <p className="font-medium">Supplier not found</p>
        <p>The requested supplier does not exist or has been deleted.</p>
        <button
          onClick={() => router.push("/suppliers")}
          className="mt-4 bg-white text-yellow-700 py-2 px-4 rounded-md hover:bg-gray-100"
        >
          Back to Suppliers
        </button>
      </div>
    );
  }

  return (
    <div className="supplier-details-page">
      {/* Sticky Header */}
      <div className="sticky top-0 z-30 bg-gradient-to-l from-white to-[#DFF9FF] shadow-sm border-b border-gray-200 backdrop-blur-sm">
        <div className="px-4 md:px-6 py-4">
          <div className="flex flex-col sm:flex-row sm:justify-between sm:items-center space-y-4 sm:space-y-0">
            <div>
              <h1 className="text-xl md:text-2xl font-bold text-gray-800">
                Supplier Details
              </h1>
            </div>
            <div className="flex flex-col sm:flex-row gap-2 sm:gap-3">
              <Link
                href={`/suppliers/${supplierId}/edit`}
                className="bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 text-center"
              >
                Edit
              </Link>
              <button
                onClick={() => router.push("/suppliers")}
                className="bg-gray-100 text-gray-700 py-2 px-4 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500"
              >
                Back to List
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="m-4 md:m-6">
        <div className="bg-white rounded-lg shadow-[0px_4px_34px_0px_rgba(0,59,113,0.16)] p-4 md:p-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 md:gap-6">
            <div>
              <h2 className="text-sm font-medium text-gray-500">Name</h2>
              <p className="text-lg font-medium">{supplier.name}</p>
            </div>
            <div>
              <h2 className="text-sm font-medium text-gray-500">Email</h2>
              <p className="text-lg font-medium">{supplier.email}</p>
            </div>
            <div>
              <h2 className="text-sm font-medium text-gray-500">Phone</h2>
              <p className="text-lg font-medium">{supplier.phone}</p>
            </div>
            <div>
              <h2 className="text-sm font-medium text-gray-500">Address</h2>
              <p className="text-lg font-medium">{supplier.address}</p>
            </div>
          </div>

          <div className="mt-8">
            <h2 className="text-lg font-semibold mb-4">Purchase Orders</h2>
            {purchaseOrders.length === 0 ? (
              <div className="text-center p-4 bg-gray-50 rounded">
                <p className="text-gray-600">
                  No purchase orders found for this supplier.
                </p>
                <Link
                  href={`/purchase-orders/create?supplierId=${supplierId}`}
                  className="mt-4 inline-block text-blue-600 hover:text-blue-800 font-medium"
                >
                  Create purchase order for this supplier
                </Link>
              </div>
            ) : (
              <>
                {/* Desktop Table View */}
                <div className="hidden lg:block overflow-x-auto">
                  <table className="min-w-full divide-y divide-gray-200">
                    <thead className="bg-gray-50">
                      <tr>
                        <th
                          scope="col"
                          className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                        >
                          PO Number
                        </th>
                        <th
                          scope="col"
                          className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                        >
                          Date
                        </th>
                        <th
                          scope="col"
                          className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                        >
                          Status
                        </th>
                        <th
                          scope="col"
                          className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                        >
                          Items
                        </th>
                      </tr>
                    </thead>
                    <tbody className="bg-white divide-y divide-gray-200">
                      {purchaseOrders.map((order) => (
                        <tr key={order.id}>
                          <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-blue-600 hover:text-blue-900">
                            <Link href={`/purchase-orders/${order.id}`}>
                              {order.orderNumber}
                            </Link>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            {formatDate(order.createdAt)}
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            <span
                              className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full 
                              ${
                                order.status === "approved"
                                  ? "bg-green-100 text-green-800"
                                  : order.status === "submitted" ||
                                    order.status === "draft"
                                  ? "bg-yellow-100 text-yellow-800"
                                  : order.status === "rejected" ||
                                    order.status === "cancelled"
                                  ? "bg-red-100 text-red-800"
                                  : "bg-blue-100 text-blue-800"
                              }`}
                            >
                              {order.status.charAt(0).toUpperCase() +
                                order.status.slice(1)}
                            </span>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            {order.items ? order.items.length : 0} items
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                {/* Mobile Card View */}
                <div className="lg:hidden space-y-4">
                  {purchaseOrders.map((order) => (
                    <div
                      key={order.id}
                      className="bg-white rounded-lg shadow border border-gray-200"
                    >
                      {/* Mobile Card Info Section */}
                      <div className="p-4">
                        <div className="flex justify-between items-start mb-3">
                          <h3 className="text-lg font-semibold text-gray-900 break-words flex-grow">
                            {order.orderNumber}
                          </h3>
                          <span
                            className={`px-2 py-1 text-xs font-semibold rounded-full ml-2 flex-shrink-0 ${
                              order.status === "approved"
                                ? "bg-green-100 text-green-800"
                                : order.status === "submitted" ||
                                  order.status === "draft"
                                ? "bg-yellow-100 text-yellow-800"
                                : order.status === "rejected" ||
                                  order.status === "cancelled"
                                ? "bg-red-100 text-red-800"
                                : "bg-blue-100 text-blue-800"
                            }`}
                          >
                            {order.status.charAt(0).toUpperCase() +
                              order.status.slice(1)}
                          </span>
                        </div>
                        <div className="space-y-2 text-sm text-gray-600">
                          <div className="flex items-center">
                            <span className="font-medium">Date:</span>
                            <span className="ml-2">
                              {formatDate(order.createdAt)}
                            </span>
                          </div>
                          <div className="flex items-center">
                            <span className="font-medium">Items:</span>
                            <span className="ml-2">
                              {order.items ? order.items.length : 0} items
                            </span>
                          </div>
                        </div>
                      </div>

                      {/* Mobile Card Actions Footer */}
                      <div className="px-4 py-3 bg-gray-50 border-t border-gray-200 rounded-b-lg">
                        <Link
                          href={`/purchase-orders/${order.id}`}
                          className="block w-full bg-blue-500 text-white py-2 px-3 rounded-lg hover:bg-blue-600 transition-colors font-medium text-sm text-center touch-manipulation"
                        >
                          View Order Details
                        </Link>
                      </div>
                    </div>
                  ))}
                </div>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
