
'use client';

import React, { useState, useEffect, useRef } from 'react';
import { Document, Page, pdfjs } from 'react-pdf';
import SignaturePad from 'react-signature-canvas';
import { 
  Save, 
  Send, 
  Download, 
  FileText,
  PenTool,
  Check,
  X,
  Loader2
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { toast } from 'sonner';
import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';

import 'react-pdf/dist/Page/AnnotationLayer.css';
import 'react-pdf/dist/Page/TextLayer.css';

// Set up PDF.js worker
if (typeof window !== 'undefined') {
  pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.mjs`;
}

interface PDFEditorProps {
  contractId: string;
  pdfData?: string;
  pdfUrl?: string;
  contractNumber: string;
  status: string;
  signatures: any[];
  onSave?: (contractId: string) => void;
  onSign?: (contractId: string) => void;
}

export function PDFEditor({
  contractId,
  pdfData: initialPdfData,
  pdfUrl: initialPdfUrl,
  contractNumber,
  status,
  signatures,
  onSave,
  onSign
}: PDFEditorProps) {
  const [pdfData, setPdfData] = useState<string | null>(initialPdfData || null);
  const [pdfUrl, setPdfUrl] = useState<string | null>(initialPdfUrl || null);
  const [numPages, setNumPages] = useState<number | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [showSignature, setShowSignature] = useState(false);
  const [signerType, setSignerType] = useState<'CLIENT' | 'COMPANY' | 'PARTNER'>('CLIENT');
  const [loading, setLoading] = useState(false);
  const [signerName, setSignerName] = useState('');
  const [signerEmail, setSignerEmail] = useState('');
  const [acceptTerms, setAcceptTerms] = useState(false);
  
  const signaturePadRef = useRef<SignaturePad>(null);

  // Check signature status
  const clientSigned = signatures?.some(s => s.signerType === 'CLIENT');
  const companySigned = signatures?.some(s => s.signerType === 'COMPANY' || s.signerType === 'PARTNER');

  // Document load success
  const onDocumentLoadSuccess = ({ numPages }: { numPages: number }) => {
    setNumPages(numPages);
  };

  // Clear signature pad
  const clearSignature = () => {
    if (signaturePadRef.current) {
      signaturePadRef.current.clear();
    }
  };

  // Submit signature
  const submitSignature = async () => {
    if (!signaturePadRef.current || signaturePadRef.current.isEmpty()) {
      toast.error('Please provide a signature');
      return;
    }

    if (!signerName || !signerEmail) {
      toast.error('Please provide signer name and email');
      return;
    }

    if (!acceptTerms) {
      toast.error('Please accept the terms');
      return;
    }

    try {
      setLoading(true);
      
      // Get signature as image data
      const signatureImage = signaturePadRef.current.toDataURL('image/png');
      
      const response = await fetch(`/api/contracts/${contractId}/sign`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          signatureData: {
            imageData: signatureImage,
            name: signerName,
            email: signerEmail,
            date: new Date().toLocaleString(),
            timestamp: Date.now()
          },
          signerType: signerType
        })
      });

      const data = await response.json();
      
      if (data.success) {
        toast.success('Contract signed successfully!');
        setPdfUrl(data.pdfUrl);
        setShowSignature(false);
        clearSignature();
        setSignerName('');
        setSignerEmail('');
        setAcceptTerms(false);
        
        if (data.isFullySigned) {
          toast.success('Contract fully signed! All parties have signed.');
        }
        
        if (onSign) {
          onSign(contractId);
        }

        // Reload the page to refresh signature status
        window.location.reload();
      } else {
        toast.error(data.error || 'Failed to sign contract');
      }
    } catch (error) {
      console.error('Error submitting signature:', error);
      toast.error('Failed to sign contract');
    } finally {
      setLoading(false);
    }
  };

  // Download PDF
  const downloadPDF = async () => {
    try {
      const response = await fetch(`/api/contracts/${contractId}/download`);
      const data = await response.json();
      
      if (data.downloadUrl) {
        // Open in new tab to trigger download
        window.open(data.downloadUrl, '_blank');
        toast.success('Download started');
      } else {
        toast.error('Failed to download contract');
      }
    } catch (error) {
      console.error('Error downloading contract:', error);
      toast.error('Failed to download contract');
    }
  };

  const pdfSource = pdfUrl || (pdfData ? `data:application/pdf;base64,${pdfData}` : null);

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <Card className="p-4 mb-4">
        <div className="flex justify-between items-center">
          <div className="flex items-center gap-3">
            <FileText className="w-8 h-8 text-primary" />
            <div>
              <h2 className="text-xl font-semibold">Contract Editor</h2>
              <p className="text-sm text-muted-foreground">Contract: {contractNumber}</p>
            </div>
          </div>
          
          <div className="flex items-center gap-2">
            <Badge variant={status === 'ACTIVE' ? 'default' : 'secondary'}>
              {status}
            </Badge>
            
            <Button 
              variant="outline"
              size="sm"
              onClick={() => {
                setShowSignature(true);
                setSignerType('CLIENT');
              }}
              disabled={loading || clientSigned}
            >
              <PenTool className="w-4 h-4 mr-1" />
              {clientSigned ? 'Client Signed' : 'Client Sign'}
            </Button>
            
            <Button 
              variant="outline"
              size="sm"
              onClick={() => {
                setShowSignature(true);
                setSignerType('COMPANY');
              }}
              disabled={loading || companySigned}
            >
              <PenTool className="w-4 h-4 mr-1" />
              {companySigned ? 'Company Signed' : 'Company Sign'}
            </Button>
            
            <Button 
              variant="outline"
              size="sm"
              onClick={downloadPDF}
              disabled={loading}
            >
              <Download className="w-4 h-4 mr-1" />
              Download
            </Button>
          </div>
        </div>
      </Card>

      {/* PDF Viewer */}
      <Card className="flex-1 overflow-auto p-4 bg-gray-50">
        {loading && (
          <div className="flex items-center justify-center h-full">
            <Loader2 className="w-8 h-8 animate-spin text-primary" />
            <p className="ml-2">Processing...</p>
          </div>
        )}
        
        {pdfSource && !loading && (
          <div className="flex flex-col items-center">
            <Document
              file={pdfSource}
              onLoadSuccess={onDocumentLoadSuccess}
              loading={
                <div className="flex items-center justify-center p-8">
                  <Loader2 className="w-8 h-8 animate-spin text-primary" />
                  <p className="ml-2">Loading PDF...</p>
                </div>
              }
              error={
                <div className="text-center p-8">
                  <p className="text-red-500">Failed to load PDF</p>
                </div>
              }
            >
              <Page 
                pageNumber={currentPage} 
                width={Math.min(800, window.innerWidth - 100)}
                renderTextLayer={true}
                renderAnnotationLayer={true}
              />
            </Document>
            
            {/* Page Navigation */}
            {numPages && numPages > 1 && (
              <div className="flex items-center gap-4 mt-4">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                  disabled={currentPage <= 1}
                >
                  Previous
                </Button>
                <span className="text-sm">
                  Page {currentPage} of {numPages}
                </span>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setCurrentPage(prev => Math.min(numPages, prev + 1))}
                  disabled={currentPage >= numPages}
                >
                  Next
                </Button>
              </div>
            )}
            
            {/* Signature Status */}
            <Card className="mt-4 p-4 w-full max-w-md">
              <h3 className="font-semibold mb-2">Signature Status</h3>
              <div className="space-y-2">
                <div className={`flex items-center gap-2 ${clientSigned ? 'text-green-600' : 'text-amber-600'}`}>
                  {clientSigned ? <Check className="w-4 h-4" /> : <X className="w-4 h-4" />}
                  <span className="text-sm">Client Signature: {clientSigned ? 'Signed' : 'Pending'}</span>
                </div>
                <div className={`flex items-center gap-2 ${companySigned ? 'text-green-600' : 'text-amber-600'}`}>
                  {companySigned ? <Check className="w-4 h-4" /> : <X className="w-4 h-4" />}
                  <span className="text-sm">Company Signature: {companySigned ? 'Signed' : 'Pending'}</span>
                </div>
              </div>
            </Card>
          </div>
        )}
      </Card>

      {/* Signature Modal */}
      <Dialog open={showSignature} onOpenChange={setShowSignature}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              Digital Signature - {signerType === 'CLIENT' ? 'Client' : 'Company'}
            </DialogTitle>
          </DialogHeader>
          
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label htmlFor="signerName">Signer Name *</Label>
                <Input
                  id="signerName"
                  value={signerName}
                  onChange={(e) => setSignerName(e.target.value)}
                  placeholder="Enter your full name"
                />
              </div>
              
              <div>
                <Label htmlFor="signerEmail">Signer Email *</Label>
                <Input
                  id="signerEmail"
                  type="email"
                  value={signerEmail}
                  onChange={(e) => setSignerEmail(e.target.value)}
                  placeholder="Enter your email"
                />
              </div>
            </div>
            
            <div>
              <Label>Draw Your Signature *</Label>
              <div className="border-2 border-dashed border-gray-300 rounded-lg mt-2 bg-white">
                <SignaturePad
                  ref={signaturePadRef}
                  canvasProps={{
                    className: 'w-full h-48',
                    style: { width: '100%', height: '192px' }
                  }}
                />
              </div>
              <Button
                type="button"
                variant="ghost"
                size="sm"
                onClick={clearSignature}
                className="mt-2"
              >
                Clear Signature
              </Button>
            </div>
            
            <div className="flex items-start space-x-2 bg-gray-50 p-4 rounded-lg">
              <Checkbox
                id="acceptTerms"
                checked={acceptTerms}
                onCheckedChange={(checked) => setAcceptTerms(checked as boolean)}
              />
              <label
                htmlFor="acceptTerms"
                className="text-sm leading-relaxed cursor-pointer"
              >
                I agree that this electronic signature is the legal equivalent 
                of my manual signature on this contract and I accept all terms and conditions.
              </label>
            </div>
          </div>
          
          <DialogFooter>
            <Button 
              variant="outline"
              onClick={() => setShowSignature(false)}
              disabled={loading}
            >
              Cancel
            </Button>
            <Button 
              onClick={submitSignature}
              disabled={loading}
            >
              {loading ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  Signing...
                </>
              ) : (
                'Sign Contract'
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
