import { useState } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { 
  FileText, 
  Calendar, 
  Receipt, 
  AlignLeft
} from "lucide-react";
import { DocumentCard } from '@/components/workflow/DocumentUpload/DocumentCard';
import { FilePreview } from '@/components/common/FilePreview/FilePreview';
import { getDocumentPreviewUrl, downloadDocument } from '@/services/workflowApi';

interface SnapshotDetailsModalProps {
  isOpen: boolean;
  onClose: () => void;
  snapshot: any;
  type: 'PROPOSAL' | 'COMPLETION';
  title?: string;
}

export function SnapshotDetailsModal({
  isOpen,
  onClose,
  snapshot,
  type,
  title
}: SnapshotDetailsModalProps) {
  // State for preview
  const [previewDoc, setPreviewDoc] = useState<{
    fileName: string;
    fileType: string;
    documentId: string;
    fileUrl?: string;
    fileSize?: number;
  } | null>(null);

  if (!snapshot) return null;

  const isProposal = type === 'PROPOSAL';

  // Helper to format currency
  const formatCurrency = (amount: number | string) => {
    return Number(amount || 0).toLocaleString('en-IN', {
      maximumFractionDigits: 2,
      style: 'currency',
      currency: 'INR'
    });
  };

  // Helper to format date
  const formatDate = (dateString: string) => {
    if (!dateString) return null;
    try {
      return new Date(dateString).toLocaleDateString('en-IN', {
        day: 'numeric',
        month: 'short',
        year: 'numeric'
      });
    } catch {
      return dateString;
    }
  };

  // Helper to check if file is previewable
  const canPreview = (fileName: string): boolean => {
    if (!fileName) return false;
    const name = fileName.toLowerCase();
    return name.endsWith('.pdf') || 
           !!name.match(/\.(jpg|jpeg|png|gif|webp)$/i);
  };

  // Helper to get file type for DocumentCard
  const getFileType = (fileName: string) => {
    const ext = (fileName || '').split('.').pop()?.toLowerCase();
    if (ext === 'pdf') return 'pdf';
    if (['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(ext || '')) return 'image';
    return 'file';
  };

  // Handle document preview click
  const handlePreview = (doc: any) => {
    const fileName = doc.fileName || doc.originalFileName || (isProposal ? 'Proposal Document' : 'Completion Document');
    const documentId = doc.documentId || '';
    const fileType = fileName.toLowerCase().endsWith('.pdf') ? 'application/pdf' : 'image/jpeg';
    
    let fileUrl = '';
    if (documentId) {
      fileUrl = getDocumentPreviewUrl(documentId);
    } else {
      // Fallback for documents without ID (using direct storageUrl)
      fileUrl = doc.storageUrl || doc.documentUrl || '';
      if (fileUrl && !fileUrl.startsWith('http')) {
        const baseUrl = import.meta.env.VITE_BASE_URL || '';
        const cleanBaseUrl = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
        const cleanFileUrl = fileUrl.startsWith('/') ? fileUrl : `/${fileUrl}`;
        fileUrl = `${cleanBaseUrl}${cleanFileUrl}`;
      }
    }

    setPreviewDoc({
      fileName,
      fileType,
      documentId,
      fileUrl,
      fileSize: doc.sizeBytes
    });
  };

  return (
    <>
      <Dialog open={isOpen} onOpenChange={onClose}>
        <DialogContent className="max-w-2xl max-h-[90vh] flex flex-col p-0 gap-0 overflow-hidden">
          <DialogHeader className="px-6 py-4 border-b">
            <DialogTitle className="flex items-center gap-2">
              {isProposal ? (
                <FileText className="w-5 h-5 text-blue-600" />
              ) : (
                <Receipt className="w-5 h-5 text-green-600" />
              )}
              {title || (isProposal ? 'Proposal Snapshot Details' : 'Completion Snapshot Details')}
            </DialogTitle>
            <DialogDescription>
              View detailed snapshot of the {isProposal ? 'proposal' : 'completion request'} at this version.
            </DialogDescription>
          </DialogHeader>
          <div className="flex-1 overflow-y-auto min-h-0 px-6 py-4">
            <div className="space-y-6">
              {/* Header Stats */}
              <div className="grid grid-cols-2 gap-4">
                <div className="p-3 bg-gray-50 rounded-lg border border-gray-100">
                  <p className="text-xs text-gray-500 font-medium mb-1">
                    {isProposal ? 'Total Budget' : 'Total Expenses'}
                  </p>
                  <p className={`text-lg font-bold ${isProposal ? 'text-blue-700' : 'text-green-700'}`}>
                    {formatCurrency(snapshot.totalBudget || snapshot.totalExpenses)}
                  </p>
                </div>
                
                {isProposal && snapshot.expectedCompletionDate && (
                  <div className="p-3 bg-gray-50 rounded-lg border border-gray-100">
                    <p className="text-xs text-gray-500 font-medium mb-1 flex items-center gap-1">
                      <Calendar className="w-3 h-3" />
                      Expected Completion
                    </p>
                    <p className="text-sm font-semibold text-gray-700">
                      {formatDate(snapshot.expectedCompletionDate)}
                    </p>
                  </div>
                )}
              </div>

              {/* Main Document */}
              {snapshot.documentUrl && (
                <div className="space-y-2">
                  <h4 className="text-sm font-semibold text-gray-900 border-b pb-1">
                    Primary Document
                  </h4>
                  <DocumentCard
                    document={{
                      documentId: '',
                      name: isProposal ? 'Proposal Document' : 'Completion Document',
                      fileType: getFileType(snapshot.documentUrl),
                      uploadedAt: new Date().toISOString()
                    }}
                    onPreview={canPreview(snapshot.documentUrl) ? () => handlePreview({
                      fileName: isProposal ? 'Proposal Document' : 'Completion Document',
                      documentUrl: snapshot.documentUrl
                    }) : undefined}
                    onDownload={async () => {
                      // Handle download for document without ID
                      let downloadUrl = snapshot.documentUrl;
                      if (!downloadUrl.startsWith('http')) {
                        const baseUrl = import.meta.env.VITE_BASE_URL || '';
                        const cleanBaseUrl = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
                        const cleanFileUrl = downloadUrl.startsWith('/') ? downloadUrl : `/${downloadUrl}`;
                        downloadUrl = `${cleanBaseUrl}${cleanFileUrl}`;
                      }
                      window.open(downloadUrl, '_blank');
                    }}
                  />
                </div>
              )}

              {/* Supporting Documents */}
              {snapshot.otherDocuments && snapshot.otherDocuments.length > 0 && (
                <div className="space-y-2">
                  <h4 className="text-sm font-semibold text-gray-900 border-b pb-1 flex items-center justify-between">
                    <span>Supporting Documents</span>
                    <Badge variant="secondary" className="text-[10px] h-5">
                      {snapshot.otherDocuments.length} Files
                    </Badge>
                  </h4>
                  <div className="space-y-2">
                    {snapshot.otherDocuments.map((doc: any, idx: number) => (
                      <DocumentCard
                        key={idx}
                        document={{
                          documentId: doc.documentId || '',
                          name: doc.originalFileName || doc.fileName || 'Supporting Document',
                          fileType: getFileType(doc.originalFileName || doc.fileName || ''),
                          uploadedAt: doc.uploadedAt || new Date().toISOString()
                        }}
                        onPreview={canPreview(doc.originalFileName || doc.fileName || '') ? () => handlePreview(doc) : undefined}
                        onDownload={doc.documentId ? downloadDocument : async () => {
                          let downloadUrl = doc.storageUrl || doc.documentUrl;
                          if (downloadUrl && !downloadUrl.startsWith('http')) {
                            const baseUrl = import.meta.env.VITE_BASE_URL || '';
                            const cleanBaseUrl = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
                            const cleanFileUrl = downloadUrl.startsWith('/') ? downloadUrl : `/${downloadUrl}`;
                            downloadUrl = `${cleanBaseUrl}${cleanFileUrl}`;
                          }
                          if (downloadUrl) window.open(downloadUrl, '_blank');
                        }}
                      />
                    ))}
                  </div>
                </div>
              )}

              {/* Cost Breakup / Expenses */}
              {(snapshot.costItems || snapshot.expenses) && (
                <div className="space-y-2">
                  <h4 className="text-sm font-semibold text-gray-900 border-b pb-1">
                    {isProposal ? 'Cost Breakdown' : 'Expenses Breakdown'}
                  </h4>
                  <div className="border rounded-md overflow-hidden text-sm">
                    <table className="w-full text-left">
                      <thead className="bg-gray-50 text-gray-600 text-xs uppercase">
                        <tr>
                          <th className="p-3 font-medium">Description</th>
                          <th className="p-3 font-medium text-right">Amount</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-gray-100">
                        {(snapshot.costItems || snapshot.expenses).length > 0 ? (
                          (snapshot.costItems || snapshot.expenses).map((item: any, idx: number) => (
                            <tr key={idx} className="bg-white hover:bg-gray-50/50">
                              <td className="p-3 text-gray-800">{item.description}</td>
                              <td className="p-3 text-right text-gray-900 font-medium tabular-nums">
                                {formatCurrency(item.amount)}
                              </td>
                            </tr>
                          ))
                        ) : (
                          <tr>
                            <td colSpan={2} className="p-4 text-center text-gray-500 italic text-xs">
                              No breakdown items available
                            </td>
                          </tr>
                        )}
                        <tr className="bg-gray-50/80 font-semibold text-gray-900 border-t-2 border-gray-100">
                          <td className="p-3">Total</td>
                          <td className="p-3 text-right tabular-nums">
                            {formatCurrency(snapshot.totalBudget || snapshot.totalExpenses)}
                          </td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
              )}

              {/* Comments */}
              {snapshot.comments && (
                <div className="space-y-2">
                  <h4 className="text-sm font-semibold text-gray-900 border-b pb-1 flex items-center gap-1">
                    <AlignLeft className="w-4 h-4" />
                    Comments
                  </h4>
                  <div className="bg-gray-50 rounded-lg p-3 text-sm text-gray-700 italic border border-gray-100">
                    {snapshot.comments}
                  </div>
                </div>
              )}
            </div>
          </div>

          <div className="px-6 py-4 border-t bg-gray-50 flex justify-end">
            <Button onClick={onClose}>Close</Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* File Preview */}
      {previewDoc && (
        <FilePreview
          fileName={previewDoc.fileName}
          fileType={previewDoc.fileType}
          fileUrl={previewDoc.fileUrl}
          fileSize={previewDoc.fileSize}
          attachmentId={previewDoc.documentId}
          onDownload={downloadDocument}
          open={!!previewDoc}
          onClose={() => setPreviewDoc(null)}
        />
      )}
    </>
  );
}
