import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { getInvoice } from "../actions/adminActions";

export default function Invoice() {
  const { id } = useParams();
  const [reservation, setReservation] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    getInvoice(id)
      .then(res => {
        setReservation(res.data);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, [id]);

  if (loading) return <p className="text-center text-lg">Loading...</p>;
  if (!reservation) return <p className="text-center text-red-500">Invoice not found</p>;

  return (
    <div className="max-w-3xl mx-auto p-6 bg-white shadow-lg rounded-lg">
      <div className="mb-6 border-b pb-4">
        <h1 className="text-3xl font-bold text-gray-800">
          Invoice #{reservation.invoice_number}
        </h1>
        <p className="text-gray-600 mt-2">
          <strong>Name:</strong> {reservation.customer_name}
        </p>
        <p className="text-gray-600">
          <strong>Date:</strong> {reservation.date}
        </p>
      </div>

      <div className="mb-6">
        <h2 className="text-xl font-semibold text-gray-700 mb-3">Items</h2>

        {reservation.items && reservation.items.length > 0 ? (
          <ul className="space-y-4">
            {reservation.items.map((item, index) => (
              <li
                key={index}
                className="flex items-center bg-gray-50 p-3 rounded-lg shadow-sm"
              >
                <img
                  src={item.img}
                  alt={item.name}
                  className="w-16 h-16 object-cover rounded-md mr-4"
                />
                <div className="flex-1">
                  <p className="font-medium text-gray-800">{item.name}</p>
                  <p className="text-gray-500 text-sm">${item.price} per item</p>
                </div>
              </li>
            ))}
          </ul>
        ) : (
          <p className="text-gray-500 italic">No items in this reservation.</p>
        )}
      </div>

      <div className="flex justify-between items-center border-t pt-4">
        {/* Remove total if you don't want it */}
        {/* <p className="text-lg font-semibold text-gray-800">
          Total: ${reservation.total}
        </p> */}
        <a
          href={reservation.pdf_link}
          target="_blank"
          rel="noopener noreferrer"
          className="bg-blue-600 text-white px-5 py-2 rounded-lg hover:bg-blue-700 transition"
        >
          Download as PDF
        </a>
      </div>
    </div>
  );
}
