'use client';

import { Suspense } from 'react';
import { useSearchParams } from 'next/navigation';
import { PDFViewer, PDFDownloadLink } from '@react-pdf/renderer';
import { ContractPDF } from './ContractPDF';
import { useState, useEffect } from 'react';

// Inner component that uses useSearchParams — must be inside Suspense
function ContractContent() {
  const searchParams = useSearchParams();
  const offerId = searchParams.get('offerId');

  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  // In a real app we'd fetch this from the server based on offerId
  const mockProperty = { title: "Luxury Villa in Janabiyah", locationGps: "26.175, 50.478" };
  const mockClient = { name: "Ahmed Al-Farsi" };
  const price = 400;

  if (!mounted) return <div className="p-10 text-center">Loading PDF engine...</div>;

  return (
    <div className="max-w-6xl mx-auto p-6 mt-8">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold text-foreground">Draft Contract {offerId ? `#${offerId}` : ''}</h1>
        <PDFDownloadLink
          document={<ContractPDF property={mockProperty} client={mockClient} price={price} contractType="lease" />}
          fileName="Contract_Agreement.pdf"
          className="bg-primary text-white px-6 py-2 rounded font-semibold hover:opacity-90"
        >
          {({ loading }: { loading: boolean }) => (loading ? 'Generating PDF...' : 'Download PDF')}
        </PDFDownloadLink>
      </div>

      <div className="w-full h-[800px] border rounded shadow overflow-hidden">
        <PDFViewer width="100%" height="100%">
          <ContractPDF property={mockProperty} client={mockClient} price={price} contractType="lease" />
        </PDFViewer>
      </div>
    </div>
  );
}

// Page wraps the inner component in Suspense — required by Next.js for useSearchParams()
export default function NewContractPage() {
  return (
    <Suspense fallback={<div className="p-10 text-center text-gray-500">Loading contract...</div>}>
      <ContractContent />
    </Suspense>
  );
}
