
'use client';

import React, { useState } from 'react';
import { FileText, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { PDFEditor } from './pdf-editor';
import { toast } from 'sonner';

interface GenerateContractButtonProps {
  quote: any;
  variant?: 'default' | 'outline' | 'ghost' | 'link';
  size?: 'default' | 'sm' | 'lg' | 'icon';
}

export function GenerateContractButton({ 
  quote,
  variant = 'default',
  size = 'default'
}: GenerateContractButtonProps) {
  const [showEditor, setShowEditor] = useState(false);
  const [loading, setLoading] = useState(false);
  const [contractData, setContractData] = useState<any>(null);

  const handleGenerateContract = async () => {
    setLoading(true);
    
    try {
      const response = await fetch('/api/contracts/generate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          quoteId: quote.id
        })
      });

      const data = await response.json();
      
      if (data.success) {
        setContractData(data.contract);
        setShowEditor(true);
        toast.success('Contract generated successfully!');
      } else {
        toast.error(data.error || 'Failed to generate contract');
      }
    } catch (error) {
      console.error('Error generating contract:', error);
      toast.error('Failed to generate contract');
    } finally {
      setLoading(false);
    }
  };

  const handleSave = (contractId: string) => {
    console.log('Contract saved:', contractId);
    toast.success('Contract saved');
  };

  const handleSign = (contractId: string) => {
    console.log('Contract signed:', contractId);
    // Refresh contract data
  };

  return (
    <>
      <Button 
        variant={variant}
        size={size}
        onClick={handleGenerateContract}
        disabled={loading}
      >
        {loading ? (
          <>
            <Loader2 className="w-4 h-4 mr-2 animate-spin" />
            Generating...
          </>
        ) : (
          <>
            <FileText className="w-4 h-4 mr-2" />
            Generate Contract
          </>
        )}
      </Button>

      {showEditor && contractData && (
        <Dialog open={showEditor} onOpenChange={setShowEditor}>
          <DialogContent className="max-w-7xl h-[90vh] p-0">
            <div className="h-full p-6">
              <PDFEditor 
                contractId={contractData.id}
                pdfData={contractData.pdfData}
                contractNumber={contractData.contractNumber}
                status={contractData.status}
                signatures={[]}
                onSave={handleSave}
                onSign={handleSign}
              />
            </div>
          </DialogContent>
        </Dialog>
      )}
    </>
  );
}
