import { useRef } from 'react';
import { calculateQuote } from '../utils/quoteCalculator';

export default function QuoteSummary({ pricing, selections, onBack, onNew }) {
  const quoteRef = useRef(null);
  const quote = calculateQuote(pricing, selections);
  const operator =
    selections.operator && typeof selections.operator === 'object'
      ? selections.operator
      : pricing.operators.find((o) => o.id === selections.operator);

  const handleDownloadPDF = async () => {
    const html2canvas = (await import('html2canvas')).default;
    const { jsPDF } = await import('jspdf');

    const element = quoteRef.current;
    if (!element) return;

    const canvas = await html2canvas(element, {
      scale: 2,
      backgroundColor: '#ffffff',
      logging: false,
    });

    const imgData = canvas.toDataURL('image/png');
    const pdf = new jsPDF('p', 'mm', 'a4');
    const margin = 14;
    const pageWidth = pdf.internal.pageSize.getWidth();
    const pageHeight = pdf.internal.pageSize.getHeight();
    const imgWidth = pageWidth - 2 * margin;
    const imgHeight = (canvas.height * imgWidth) / canvas.width;

    let heightLeft = imgHeight;
    let position = margin;

    pdf.addImage(imgData, 'PNG', margin, position, imgWidth, imgHeight);
    heightLeft -= pageHeight - margin;

    while (heightLeft > 0) {
      position -= pageHeight - margin;
      pdf.addPage();
      pdf.addImage(imgData, 'PNG', margin, position, imgWidth, imgHeight);
      heightLeft -= pageHeight - margin;
    }

    const modelName = operator?.tiltModel || operator?.model || 'Quote';
    pdf.save('Gate_Quote_' + modelName + '.pdf');
  };

  return (
    <div>
      <div className="flex items-center gap-2 mb-6">
        <button
          onClick={onBack}
          className="p-1.5 rounded-lg hover:bg-gray-100 text-gray-500 transition-colors"
        >
          <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
          </svg>
        </button>
        <div>
          <h2 className="text-xl font-semibold text-gray-900">
            Quote Summary
          </h2>
          <p className="text-gray-500">
            Review your selection and itemized cost estimate
          </p>
        </div>
      </div>

      <div ref={quoteRef} className="bg-white p-6">
        <div className="border-b border-gray-300 pb-4 mb-4">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-2xl font-bold text-gray-900">
                Gate Operator Quote
              </h3>
              <p className="text-sm text-gray-500">
                Quotation Date: {new Date().toLocaleDateString('en-CA')}
              </p>
            </div>
            <div className="text-right">
              <div className="text-lg font-bold text-blue-600">
                {pricing.currency.symbol}
                {quote.total.toLocaleString(pricing.currency.locale, {
                  minimumFractionDigits: 2,
                  maximumFractionDigits: 2,
                })}
              </div>
              <div className="text-sm text-gray-500">Estimated Total</div>
            </div>
          </div>
        </div>

        {operator && (
          <div className="bg-gray-50 rounded-lg p-4 mb-4 flex items-start gap-4">
            {operator.imageFile && !operator.tiltModel && (
              <img
                src={'/images/operators/' + operator.imageFile}
                alt={operator.name}
                className="w-24 h-24 rounded-lg object-cover shrink-0 border border-gray-200"
                onError={(e) => { e.target.style.display = 'none'; }}
              />
            )}
            <div>
              <div className="text-sm font-semibold text-gray-500 uppercase tracking-wider mb-1">
                Selected Operator
              </div>
              <div className="font-semibold text-gray-900">
                {operator.tiltName || operator.name}
              </div>
              <div className="text-sm text-gray-500">
                Model: {operator.tiltModel || operator.model}
              </div>
              {operator.tiltDescription && (
                <div className="text-sm text-gray-500">
                  {operator.tiltDescription}
                </div>
              )}
            </div>
          </div>
        )}

        {quote.items.length > 0 ? (
          <table className="w-full mb-4">
            <thead>
              <tr className="border-b border-gray-200">
                <th className="text-left py-3 px-2 text-xs font-semibold text-gray-500 uppercase tracking-wider">
                  Item
                </th>
                <th className="text-center py-3 px-2 text-xs font-semibold text-gray-500 uppercase tracking-wider">
                  Qty
                </th>
                <th className="text-right py-3 px-2 text-xs font-semibold text-gray-500 uppercase tracking-wider">
                  Unit Price
                </th>
                <th className="text-right py-3 px-2 text-xs font-semibold text-gray-500 uppercase tracking-wider">
                  Total
                </th>
              </tr>
            </thead>
            <tbody>
              {quote.items.map((item, i) => (
                <tr key={i} className="border-b border-gray-100">
                  <td className="py-3 px-2">
                    <div className="text-sm font-medium text-gray-900">
                      {item.name}
                    </div>
                    <div className="text-xs text-gray-400">{item.category}</div>
                  </td>
                  <td className="py-3 px-2 text-center text-sm text-gray-700">
                    {item.qty}
                  </td>
                  <td className="py-3 px-2 text-right text-sm text-gray-700">
                    {pricing.currency.symbol}
                    {item.unitPrice.toLocaleString(pricing.currency.locale, {
                      minimumFractionDigits: 2,
                      maximumFractionDigits: 2,
                    })}
                  </td>
                  <td className="py-3 px-2 text-right text-sm font-medium text-gray-900">
                    {pricing.currency.symbol}
                    {item.lineTotal.toLocaleString(pricing.currency.locale, {
                      minimumFractionDigits: 2,
                      maximumFractionDigits: 2,
                    })}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <div className="text-center py-8 text-gray-500">
            No items selected. Please go back and make your selections.
          </div>
        )}

        <div className="border-t border-gray-300 pt-4">
          <div className="flex justify-between text-lg font-bold text-gray-900">
            <span>Total Cost</span>
            <span>
              {pricing.currency.symbol}
              {quote.subtotal.toLocaleString(pricing.currency.locale, {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2,
              })}
            </span>
          </div>
        </div>

        <div className="mt-4 text-xs text-gray-400 text-center border-t border-gray-200 pt-4">
          <p>
            This is a preliminary cost estimate. Final pricing may vary based on
            site-specific requirements.
          </p>
          <p className="mt-1">
            Generated by Gate Operator Quotation System &mdash; {new Date().toLocaleDateString('en-CA')}
          </p>
        </div>
      </div>

      <div className="flex items-center justify-between pt-6 border-t border-gray-200 mt-6">
        <button
          onClick={onBack}
          className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg font-medium hover:bg-gray-50 transition-colors"
        >
          Back
        </button>
        <div className="flex gap-3">
          <button
            onClick={handleDownloadPDF}
            className="px-6 py-2.5 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700 transition-colors flex items-center gap-2"
          >
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
            </svg>
            Download PDF
          </button>
          <button
            onClick={onNew}
            className="px-4 py-2.5 border border-gray-300 text-gray-700 rounded-lg font-medium hover:bg-gray-50 transition-colors"
          >
            New Quote
          </button>
        </div>
      </div>
    </div>
  );
}
