'use client';

import { useState, useCallback } from 'react';
import { PDFDocument, rgb } from 'pdf-lib';
import { FileUpload } from './file-upload';
import { ImageSelector } from './image-selector';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Progress } from '@/components/ui/progress';
import { Download, FileText, Image as ImageIcon, Loader2 } from 'lucide-react';
import { toast } from 'sonner';

export function PDFEditor() {
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [selectedHeader, setSelectedHeader] = useState<string | null>(null);
  const [selectedFooter, setSelectedFooter] = useState<string | null>(null);
  const [processing, setProcessing] = useState(false);
  const [progress, setProgress] = useState(0);

  const handleFileSelect = useCallback((file: any) => {
    setSelectedFile(file);
    toast.success('PDF file selected successfully');
  }, []);


  const handleClearFile = useCallback(() => {
    setSelectedFile(null);
    setSelectedHeader(null);
    setSelectedFooter(null);
    setProgress(0);
  }, []);

  const loadImageAsBytes = async (imagePath: string): Promise<Uint8Array> => {
    const response = await fetch(imagePath);
    const arrayBuffer = await response.arrayBuffer();
    return new Uint8Array(arrayBuffer);
  };

  const processPDF = async () => {
    if (!selectedFile) {
      toast.error('Please select a PDF file');
      return;
    }

    if (!selectedHeader && !selectedFooter) {
      toast.error('Please select at least one header or footer');
      return;
    }

    setProcessing(true);
    setProgress(0);

    try {
      // Read the PDF file
      const pdfArrayBuffer = await selectedFile.arrayBuffer();
      const pdfDoc = await PDFDocument.load(pdfArrayBuffer);

      setProgress(20);

      // Load header and footer images if selected
      let headerImageBytes: Uint8Array | null = null;
      let footerImageBytes: Uint8Array | null = null;

      if (selectedHeader) {
        headerImageBytes = await loadImageAsBytes(selectedHeader);
      }

      if (selectedFooter) {
        footerImageBytes = await loadImageAsBytes(selectedFooter);
      }

      setProgress(40);

      // Get page dimensions (A4: 595.28 x 841.89 points)
      const pages = pdfDoc.getPages();
      const totalPages = pages.length;

      // Process each page
      for (let i = 0; i < totalPages; i++) {
        const page = pages[i];
        const { width, height } = page.getSize();

        // Add header if selected
        if (headerImageBytes) {
          let headerImage;

          // Determine image type and embed accordingly
          if (selectedHeader!.toLowerCase().includes('.png')) {
            headerImage = await pdfDoc.embedPng(headerImageBytes);
          } else {
            headerImage = await pdfDoc.embedJpg(headerImageBytes);
          }

          // Calculate header dimensions (maintain aspect ratio, fit to page width)
          const headerAspectRatio = headerImage.width / headerImage.height;
          const headerWidth = width * 0.9; // 90% of page width
          const headerHeight = headerWidth / headerAspectRatio;

          // Position header at top of page
          page.drawImage(headerImage, {
            x: (width - headerWidth) / 2,
            y: height - headerHeight - 10, // 20 points from top
            width: headerWidth,
            height: headerHeight,
          });
        }

        // Add footer if selected
        if (footerImageBytes) {
          let footerImage;

          // Determine image type and embed accordingly
          if (selectedFooter!.toLowerCase().includes('.png')) {
            footerImage = await pdfDoc.embedPng(footerImageBytes);
          } else {
            footerImage = await pdfDoc.embedJpg(footerImageBytes);
          }

          // Calculate footer dimensions (maintain aspect ratio, fit to page width)
          const footerAspectRatio = footerImage.width / footerImage.height;
          const footerWidth = width * 0.9; // 90% of page width
          const footerHeight = footerWidth / footerAspectRatio;

          // Position footer at bottom of page
          page.drawImage(footerImage, {
            x: (width - footerWidth) / 2,
            y: 10, // 20 points from bottom
            width: footerWidth,
            height: footerHeight,
          });
        }

        // Update progress
        setProgress(40 + (i / totalPages) * 50);
      }

      setProgress(90);

      // Save the modified PDF
      const pdfBytes = await pdfDoc.save();

      setProgress(100);

      // Create download link
      const blob = new Blob([pdfBytes], { type: 'application/pdf' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `${selectedFile.name.replace('.pdf', '')}_with_headers_footers.pdf`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);

      toast.success('PDF processed and downloaded successfully!');
    } catch (error) {
      console.error('Error processing PDF:', error);
      toast.error('Error processing PDF. Please try again.');
    } finally {
      setProcessing(false);
      setTimeout(() => setProgress(0), 1000);
    }
  };

  const canProcess = selectedFile && (selectedHeader || selectedFooter);

  return (
    <div className="max-w-6xl mx-auto p-6 space-y-8">
      {/* Header */}
      <div className="text-center space-y-2">
        <h1 className="text-3xl font-bold text-gray-900">Health Lab Solution</h1>
        <p className="text-gray-600">
          Upload a PDF and add custom headers and footers to all pages
        </p>
      </div>

      {/* File Upload */}
      <Card className="p-6">
        <h2 className="text-xl font-semibold text-gray-900 mb-4 flex items-center gap-2">
          <FileText className="h-5 w-5" />
          Upload PDF
        </h2>
        <FileUpload
          onFileSelect={handleFileSelect}
          selectedFile={selectedFile}
          onClearFile={handleClearFile}
        />
      </Card>

      {/* Image Selectors */}
      {selectedFile && (
        <div className="grid md:grid-cols-2 gap-6">
          <Card className="p-6">
            <div className="flex items-center gap-2 mb-4">
              <ImageIcon className="h-5 w-5" />
              <h2 className="text-xl font-semibold text-gray-900">Headers</h2>
            </div>
            <ImageSelector
              type="header"
              selectedImage={selectedHeader}
              onImageSelect={setSelectedHeader}
            />
          </Card>

          <Card className="p-6">
            <div className="flex items-center gap-2 mb-4">
              <ImageIcon className="h-5 w-5" />
              <h2 className="text-xl font-semibold text-gray-900">Footers</h2>
            </div>
            <ImageSelector
              type="footer"
              selectedImage={selectedFooter}
              onImageSelect={setSelectedFooter}
            />
          </Card>
        </div>
      )}

      {/* Process & Download */}
      {selectedFile && (
        <Card className="p-6">
          <div className="space-y-4">
            <h2 className="text-xl font-semibold text-gray-900 flex items-center gap-2">
              <Download className="h-5 w-5" />
              Process & Download
            </h2>

            {progress > 0 && (
              <div className="space-y-2">
                <div className="flex justify-between text-sm text-gray-600">
                  <span>Processing PDF...</span>
                  <span>{Math.round(progress)}%</span>
                </div>
                <Progress value={progress} className="h-2" />
              </div>
            )}

            <div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between">
              <div className="space-y-1">
                <p className="text-sm text-gray-600">
                  Selected: {selectedFile.name}
                </p>
                <p className="text-sm text-gray-500">
                  {selectedHeader && 'Header selected'}
                  {selectedHeader && selectedFooter && ' • '}
                  {selectedFooter && 'Footer selected'}
                </p>
              </div>

              <Button
                onClick={processPDF}
                disabled={!canProcess || processing}
                size="lg"
                className="w-full sm:w-auto"
              >
                {processing ? (
                  <>
                    <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                    Processing...
                  </>
                ) : (
                  <>
                    <Download className="h-4 w-4 mr-2" />
                    Process & Download PDF
                  </>
                )}
              </Button>
            </div>
          </div>
        </Card>
      )}
    </div>
  );
}