/**
 * DealerCompletionDocumentsModal Component
 * Modal for Step 5: Activity Completion Documents
 * Allows dealers to upload completion documents, photos, expenses, and provide completion details
 */

import { useState, useRef, useMemo, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { Upload, Plus, X, Calendar, FileText, Image, Receipt, CircleAlert, CheckCircle2, Eye, Download } from 'lucide-react';
import { toast } from 'sonner';
import '@/components/common/FilePreview/FilePreview.css';

interface ExpenseItem {
  id: string;
  description: string;
  amount: number;
}

interface DealerCompletionDocumentsModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSubmit: (data: {
    activityCompletionDate: string;
    numberOfParticipants?: number;
    closedExpenses: ExpenseItem[];
    totalClosedExpenses: number;
    completionDocuments: File[];
    activityPhotos: File[];
    invoicesReceipts?: File[];
    attendanceSheet?: File;
    completionDescription: string;
  }) => Promise<void>;
  dealerName?: string;
  activityName?: string;
  requestId?: string;
}

export function DealerCompletionDocumentsModal({
  isOpen,
  onClose,
  onSubmit,
  dealerName = 'Jaipur Royal Enfield',
  activityName = 'Activity',
  requestId: _requestId,
}: DealerCompletionDocumentsModalProps) {
  const [activityCompletionDate, setActivityCompletionDate] = useState('');
  const [numberOfParticipants, setNumberOfParticipants] = useState('');
  const [expenseItems, setExpenseItems] = useState<ExpenseItem[]>([]);
  const [completionDocuments, setCompletionDocuments] = useState<File[]>([]);
  const [activityPhotos, setActivityPhotos] = useState<File[]>([]);
  const [invoicesReceipts, setInvoicesReceipts] = useState<File[]>([]);
  const [attendanceSheet, setAttendanceSheet] = useState<File | null>(null);
  const [completionDescription, setCompletionDescription] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [previewFile, setPreviewFile] = useState<{ file: File; url: string } | null>(null);

  const completionDocsInputRef = useRef<HTMLInputElement>(null);
  const photosInputRef = useRef<HTMLInputElement>(null);
  const invoicesInputRef = useRef<HTMLInputElement>(null);
  const attendanceInputRef = useRef<HTMLInputElement>(null);

  // Helper function to check if file can be previewed
  const canPreviewFile = (file: File): boolean => {
    const type = file.type.toLowerCase();
    const name = file.name.toLowerCase();
    return type.includes('image') || 
           type.includes('pdf') || 
           name.endsWith('.pdf') ||
           name.endsWith('.jpg') || 
           name.endsWith('.jpeg') || 
           name.endsWith('.png') || 
           name.endsWith('.gif') ||
           name.endsWith('.webp');
  };

  // Cleanup object URLs when component unmounts or file changes
  useEffect(() => {
    return () => {
      if (previewFile?.url) {
        URL.revokeObjectURL(previewFile.url);
      }
    };
  }, [previewFile]);

  // Handle file preview
  const handlePreviewFile = (file: File) => {
    if (!canPreviewFile(file)) {
      toast.error('Preview is only available for images and PDF files');
      return;
    }
    
    // Cleanup previous preview URL
    if (previewFile?.url) {
      URL.revokeObjectURL(previewFile.url);
    }
    
    const url = URL.createObjectURL(file);
    setPreviewFile({ file, url });
  };

  // Handle download file (for non-previewable files)
  const handleDownloadFile = (file: File) => {
    const url = URL.createObjectURL(file);
    const a = document.createElement('a');
    a.href = url;
    a.download = file.name;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  // Calculate total closed expenses
  const totalClosedExpenses = useMemo(() => {
    return expenseItems.reduce((sum, item) => sum + (item.amount || 0), 0);
  }, [expenseItems]);

  // Check if all required fields are filled
  const isFormValid = useMemo(() => {
    const hasCompletionDate = activityCompletionDate !== '';
    const hasDocuments = completionDocuments.length > 0;
    const hasPhotos = activityPhotos.length > 0;
    const hasDescription = completionDescription.trim().length > 0;

    return hasCompletionDate && hasDocuments && hasPhotos && hasDescription;
  }, [activityCompletionDate, completionDocuments, activityPhotos, completionDescription]);

  // Get today's date in YYYY-MM-DD format for max date
  const maxDate = new Date().toISOString().split('T')[0];

  const handleAddExpense = () => {
    setExpenseItems([
      ...expenseItems,
      { id: Date.now().toString(), description: '', amount: 0 },
    ]);
  };

  const handleExpenseChange = (id: string, field: 'description' | 'amount', value: string | number) => {
    setExpenseItems(
      expenseItems.map((item) =>
        item.id === id ? { ...item, [field]: value } : item
      )
    );
  };

  const handleRemoveExpense = (id: string) => {
    setExpenseItems(expenseItems.filter((item) => item.id !== id));
  };

  const handleCompletionDocsChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    if (files.length > 0) {
      // Validate file types
      const allowedTypes = ['.pdf', '.doc', '.docx', '.zip', '.rar'];
      const invalidFiles = files.filter(
        (file) => !allowedTypes.some((ext) => file.name.toLowerCase().endsWith(ext))
      );
      if (invalidFiles.length > 0) {
        toast.error('Please upload PDF, DOC, DOCX, ZIP, or RAR files only');
        return;
      }
      setCompletionDocuments([...completionDocuments, ...files]);
    }
  };

  const handleRemoveCompletionDoc = (index: number) => {
    setCompletionDocuments(completionDocuments.filter((_, i) => i !== index));
  };

  const handlePhotosChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    if (files.length > 0) {
      // Validate image files
      const invalidFiles = files.filter(
        (file) => !file.type.startsWith('image/')
      );
      if (invalidFiles.length > 0) {
        toast.error('Please upload image files only (JPG, PNG, etc.)');
        return;
      }
      setActivityPhotos([...activityPhotos, ...files]);
    }
  };

  const handleRemovePhoto = (index: number) => {
    setActivityPhotos(activityPhotos.filter((_, i) => i !== index));
  };

  const handleInvoicesChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    if (files.length > 0) {
      // Validate file types
      const allowedTypes = ['.pdf', '.jpg', '.jpeg', '.png'];
      const invalidFiles = files.filter(
        (file) => !allowedTypes.some((ext) => file.name.toLowerCase().endsWith(ext))
      );
      if (invalidFiles.length > 0) {
        toast.error('Please upload PDF, JPG, or PNG files only');
        return;
      }
      setInvoicesReceipts([...invoicesReceipts, ...files]);
    }
  };

  const handleRemoveInvoice = (index: number) => {
    setInvoicesReceipts(invoicesReceipts.filter((_, i) => i !== index));
  };

  const handleAttendanceChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      // Validate file types
      const allowedTypes = ['.pdf', '.xlsx', '.xls', '.csv'];
      const fileExtension = '.' + file.name.split('.').pop()?.toLowerCase();
      if (!allowedTypes.includes(fileExtension)) {
        toast.error('Please upload PDF, Excel, or CSV files only');
        return;
      }
      setAttendanceSheet(file);
    }
  };

  const handleSubmit = async () => {
    if (!isFormValid) {
      toast.error('Please fill all required fields');
      return;
    }

    // Filter valid expense items
    const validExpenses = expenseItems.filter(
      (item) => item.description.trim() !== '' && item.amount > 0
    );

    try {
      setSubmitting(true);
      await onSubmit({
        activityCompletionDate,
        numberOfParticipants: numberOfParticipants ? parseInt(numberOfParticipants) : undefined,
        closedExpenses: validExpenses,
        totalClosedExpenses,
        completionDocuments,
        activityPhotos,
        invoicesReceipts: invoicesReceipts.length > 0 ? invoicesReceipts : undefined,
        attendanceSheet: attendanceSheet || undefined,
        completionDescription,
      });
      handleReset();
      onClose();
    } catch (error) {
      console.error('Failed to submit completion documents:', error);
      toast.error('Failed to submit completion documents. Please try again.');
    } finally {
      setSubmitting(false);
    }
  };

  const handleReset = () => {
    // Cleanup preview URL if exists
    if (previewFile?.url) {
      URL.revokeObjectURL(previewFile.url);
    }
    setPreviewFile(null);
    setActivityCompletionDate('');
    setNumberOfParticipants('');
    setExpenseItems([]);
    setCompletionDocuments([]);
    setActivityPhotos([]);
    setInvoicesReceipts([]);
    setAttendanceSheet(null);
    setCompletionDescription('');
    if (completionDocsInputRef.current) completionDocsInputRef.current.value = '';
    if (photosInputRef.current) photosInputRef.current.value = '';
    if (invoicesInputRef.current) invoicesInputRef.current.value = '';
    if (attendanceInputRef.current) attendanceInputRef.current.value = '';
  };

  const handleClose = () => {
    if (!submitting) {
      handleReset();
      onClose();
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-lg max-w-4xl max-h-[90vh] overflow-y-auto overflow-x-hidden">
        <DialogHeader>
          <DialogTitle className="font-semibold flex items-center gap-2 text-2xl">
            <Upload className="w-6 h-6 text-[--re-green]" />
            Activity Completion Documents
          </DialogTitle>
          <DialogDescription className="text-base">
            Step 5: Upload completion proof and final documents
          </DialogDescription>
          <div className="space-y-1 mt-2 text-sm text-gray-600">
            <div>
              <strong>Dealer:</strong> {dealerName}
            </div>
            <div>
              <strong>Activity:</strong> {activityName}
            </div>
            <div className="mt-2">
              Please upload completion documents, photos, and provide details about the completed activity.
            </div>
          </div>
        </DialogHeader>

        <div className="space-y-6 py-4">
          {/* Activity Completion Date */}
          <div className="space-y-2">
            <Label className="text-base font-semibold flex items-center gap-2" htmlFor="completionDate">
              <Calendar className="w-4 h-4" />
              Activity Completion Date *
            </Label>
            <Input
              type="date"
              id="completionDate"
              max={maxDate}
              value={activityCompletionDate}
              onChange={(e) => setActivityCompletionDate(e.target.value)}
            />
          </div>

          {/* Closed Expenses Section */}
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <h3 className="font-semibold text-lg">Closed Expenses</h3>
                <Badge className="bg-secondary text-secondary-foreground text-xs">Optional</Badge>
              </div>
              <Button
                type="button"
                onClick={handleAddExpense}
                className="bg-[#2d4a3e] hover:bg-[#1f3329] text-white"
                size="sm"
              >
                <Plus className="w-4 h-4 mr-1" />
                Add Expense
              </Button>
            </div>
            <div className="space-y-3">
              {expenseItems.map((item) => (
                <div key={item.id} className="flex gap-2 items-start">
                  <div className="flex-1">
                    <Input
                      placeholder="Item name (e.g., Venue rental, Refreshments, Printing)"
                      value={item.description}
                      onChange={(e) =>
                        handleExpenseChange(item.id, 'description', e.target.value)
                      }
                    />
                  </div>
                  <div className="w-40">
                    <Input
                      type="number"
                      placeholder="Amount"
                      min="0"
                      step="0.01"
                      value={item.amount || ''}
                      onChange={(e) =>
                        handleExpenseChange(item.id, 'amount', parseFloat(e.target.value) || 0)
                      }
                    />
                  </div>
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    className="mt-0.5 hover:bg-red-100 hover:text-red-700"
                    onClick={() => handleRemoveExpense(item.id)}
                  >
                    <X className="w-4 h-4" />
                  </Button>
                </div>
              ))}
              {expenseItems.length === 0 && (
                <p className="text-sm text-gray-500 italic">
                  No expenses added. Click "Add Expense" to add expense items.
                </p>
              )}
              {expenseItems.length > 0 && totalClosedExpenses > 0 && (
                <div className="pt-2 border-t">
                  <div className="flex justify-between items-center">
                    <span className="font-semibold">Total Closed Expenses:</span>
                    <span className="font-semibold text-lg">
                      ₹{totalClosedExpenses.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                    </span>
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Completion Evidence Section */}
          <div className="space-y-4">
            <div className="flex items-center gap-2">
              <h3 className="font-semibold text-lg">Completion Evidence</h3>
              <Badge className="bg-destructive text-white text-xs">Required</Badge>
            </div>

            {/* Completion Documents */}
            <div>
              <Label className="text-base font-semibold flex items-center gap-2">
                <FileText className="w-4 h-4" />
                Completion Documents *
              </Label>
              <p className="text-sm text-gray-600 mb-2">
                Upload documents proving activity completion (reports, certificates, etc.) - Can upload multiple files or ZIP folder
              </p>
              <div
                className={`border-2 border-dashed rounded-lg p-4 transition-all duration-200 ${
                  completionDocuments.length > 0
                    ? 'border-green-500 bg-green-50 hover:border-green-600'
                    : 'border-gray-300 hover:border-blue-500 bg-white'
                }`}
              >
                <input
                  ref={completionDocsInputRef}
                  type="file"
                  multiple
                  accept=".pdf,.doc,.docx,.zip,.rar"
                  className="hidden"
                  id="completionDocs"
                  onChange={handleCompletionDocsChange}
                />
                <label
                  htmlFor="completionDocs"
                  className="cursor-pointer flex flex-col items-center gap-2"
                >
                  {completionDocuments.length > 0 ? (
                    <>
                      <CheckCircle2 className="w-8 h-8 text-green-600" />
                      <div className="flex flex-col items-center gap-1">
                        <span className="text-sm font-semibold text-green-700">
                          {completionDocuments.length} document{completionDocuments.length !== 1 ? 's' : ''} selected
                        </span>
                        <span className="text-xs text-green-600">
                          Click to add more documents
                        </span>
                      </div>
                    </>
                  ) : (
                    <>
                      <Upload className="w-8 h-8 text-gray-400" />
                      <span className="text-sm text-gray-600">
                        Click to upload documents (PDF, DOC, ZIP - multiple files allowed)
                      </span>
                    </>
                  )}
                </label>
              </div>
              {completionDocuments.length > 0 && (
                <div className="mt-3 space-y-2">
                  <p className="text-xs font-medium text-gray-600 mb-1">
                    Selected Documents ({completionDocuments.length}):
                  </p>
                  {completionDocuments.map((file, index) => (
                    <div
                      key={index}
                      className="flex items-start justify-between bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200 p-3 rounded-lg text-sm shadow-sm hover:shadow-md transition-shadow w-full"
                    >
                      <div className="flex items-start gap-2 flex-1 min-w-0 pr-2">
                        <FileText className="w-4 h-4 text-green-600 flex-shrink-0 mt-0.5" />
                        <span className="text-gray-800 font-medium break-words break-all">{file.name}</span>
                      </div>
                      <div className="flex items-center gap-1 flex-shrink-0 ml-2">
                        {canPreviewFile(file) && (
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            className="h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700"
                            onClick={() => handlePreviewFile(file)}
                            title="Preview file"
                          >
                            <Eye className="w-3.5 h-3.5" />
                          </Button>
                        )}
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          className="h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700"
                          onClick={() => handleDownloadFile(file)}
                          title="Download file"
                        >
                          <Download className="w-3.5 h-3.5" />
                        </Button>
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          className="h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700"
                          onClick={() => handleRemoveCompletionDoc(index)}
                          title="Remove document"
                        >
                          <X className="w-4 h-4" />
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* Activity Photos */}
            <div>
              <Label className="text-base font-semibold flex items-center gap-2">
                <Image className="w-4 h-4" />
                Activity Photos *
              </Label>
              <p className="text-sm text-gray-600 mb-2">
                Upload photos from the completed activity (event photos, installations, etc.)
              </p>
              <div
                className={`border-2 border-dashed rounded-lg p-4 transition-all duration-200 ${
                  activityPhotos.length > 0
                    ? 'border-green-500 bg-green-50 hover:border-green-600'
                    : 'border-gray-300 hover:border-blue-500 bg-white'
                }`}
              >
                <input
                  ref={photosInputRef}
                  type="file"
                  multiple
                  accept="image/*"
                  className="hidden"
                  id="completionPhotos"
                  onChange={handlePhotosChange}
                />
                <label
                  htmlFor="completionPhotos"
                  className="cursor-pointer flex flex-col items-center gap-2"
                >
                  {activityPhotos.length > 0 ? (
                    <>
                      <CheckCircle2 className="w-8 h-8 text-green-600" />
                      <div className="flex flex-col items-center gap-1">
                        <span className="text-sm font-semibold text-green-700">
                          {activityPhotos.length} photo{activityPhotos.length !== 1 ? 's' : ''} selected
                        </span>
                        <span className="text-xs text-green-600">
                          Click to add more photos
                        </span>
                      </div>
                    </>
                  ) : (
                    <>
                      <Image className="w-8 h-8 text-gray-400" />
                      <span className="text-sm text-gray-600">
                        Click to upload photos (JPG, PNG - multiple files allowed)
                      </span>
                    </>
                  )}
                </label>
              </div>
              {activityPhotos.length > 0 && (
                <div className="mt-3 space-y-2">
                  <p className="text-xs font-medium text-gray-600 mb-1">
                    Selected Photos ({activityPhotos.length}):
                  </p>
                  {activityPhotos.map((file, index) => (
                    <div
                      key={index}
                      className="flex items-start justify-between bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200 p-3 rounded-lg text-sm shadow-sm hover:shadow-md transition-shadow w-full"
                    >
                      <div className="flex items-start gap-2 flex-1 min-w-0 pr-2">
                        <Image className="w-4 h-4 text-green-600 flex-shrink-0 mt-0.5" />
                        <span className="text-gray-800 font-medium break-words break-all">{file.name}</span>
                      </div>
                      <div className="flex items-center gap-1 flex-shrink-0 ml-2">
                        {canPreviewFile(file) && (
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            className="h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700"
                            onClick={() => handlePreviewFile(file)}
                            title="Preview photo"
                          >
                            <Eye className="w-3.5 h-3.5" />
                          </Button>
                        )}
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          className="h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700"
                          onClick={() => handleDownloadFile(file)}
                          title="Download photo"
                        >
                          <Download className="w-3.5 h-3.5" />
                        </Button>
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          className="h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700"
                          onClick={() => handleRemovePhoto(index)}
                          title="Remove photo"
                        >
                          <X className="w-4 h-4" />
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>

          {/* Supporting Documents Section */}
          <div className="space-y-4">
            <div className="flex items-center gap-2">
              <h3 className="font-semibold text-lg">Supporting Documents</h3>
              <Badge className="bg-secondary text-secondary-foreground text-xs">Optional</Badge>
            </div>

            {/* Invoices/Receipts */}
            <div>
              <Label className="text-base font-semibold flex items-center gap-2">
                <Receipt className="w-4 h-4" />
                Invoices / Receipts
              </Label>
              <p className="text-sm text-gray-600 mb-2">
                Upload invoices and receipts for expenses incurred
              </p>
              <div
                className={`border-2 border-dashed rounded-lg p-4 transition-all duration-200 ${
                  invoicesReceipts.length > 0
                    ? 'border-blue-500 bg-blue-50 hover:border-blue-600'
                    : 'border-gray-300 hover:border-blue-500 bg-white'
                }`}
              >
                <input
                  ref={invoicesInputRef}
                  type="file"
                  multiple
                  accept=".pdf,.jpg,.jpeg,.png"
                  className="hidden"
                  id="invoiceReceipts"
                  onChange={handleInvoicesChange}
                />
                <label
                  htmlFor="invoiceReceipts"
                  className="cursor-pointer flex flex-col items-center gap-2"
                >
                  {invoicesReceipts.length > 0 ? (
                    <>
                      <CheckCircle2 className="w-8 h-8 text-blue-600" />
                      <div className="flex flex-col items-center gap-1">
                        <span className="text-sm font-semibold text-blue-700">
                          {invoicesReceipts.length} document{invoicesReceipts.length !== 1 ? 's' : ''} selected
                        </span>
                        <span className="text-xs text-blue-600">
                          Click to add more documents
                        </span>
                      </div>
                    </>
                  ) : (
                    <>
                      <Receipt className="w-8 h-8 text-gray-400" />
                      <span className="text-sm text-gray-600">
                        Click to upload invoices/receipts (PDF, JPG, PNG)
                      </span>
                    </>
                  )}
                </label>
              </div>
              {invoicesReceipts.length > 0 && (
                <div className="mt-3 space-y-2">
                  <p className="text-xs font-medium text-gray-600 mb-1">
                    Selected Documents ({invoicesReceipts.length}):
                  </p>
                  {invoicesReceipts.map((file, index) => (
                    <div
                      key={index}
                      className="flex items-start justify-between bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 p-3 rounded-lg text-sm shadow-sm hover:shadow-md transition-shadow w-full"
                    >
                      <div className="flex items-start gap-2 flex-1 min-w-0 pr-2">
                        <Receipt className="w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5" />
                        <span className="text-gray-800 font-medium break-words break-all">{file.name}</span>
                      </div>
                      <div className="flex items-center gap-1 flex-shrink-0 ml-2">
                        {canPreviewFile(file) && (
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            className="h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700"
                            onClick={() => handlePreviewFile(file)}
                            title="Preview file"
                          >
                            <Eye className="w-3.5 h-3.5" />
                          </Button>
                        )}
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          className="h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700"
                          onClick={() => handleDownloadFile(file)}
                          title="Download file"
                        >
                          <Download className="w-3.5 h-3.5" />
                        </Button>
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          className="h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700"
                          onClick={() => handleRemoveInvoice(index)}
                          title="Remove document"
                        >
                          <X className="w-4 h-4" />
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* Attendance Sheet */}
            <div>
              <Label className="text-base font-semibold">
                Attendance Sheet / Participant List
              </Label>
              <p className="text-sm text-gray-600 mb-2">
                Upload attendance records or participant lists (if applicable)
              </p>
              <div
                className={`border-2 border-dashed rounded-lg p-4 transition-all duration-200 ${
                  attendanceSheet
                    ? 'border-blue-500 bg-blue-50 hover:border-blue-600'
                    : 'border-gray-300 hover:border-blue-500 bg-white'
                }`}
              >
                <input
                  ref={attendanceInputRef}
                  type="file"
                  accept=".pdf,.xlsx,.xls,.csv"
                  className="hidden"
                  id="attendanceDoc"
                  onChange={handleAttendanceChange}
                />
                <label
                  htmlFor="attendanceDoc"
                  className="cursor-pointer flex flex-col items-center gap-2"
                >
                  {attendanceSheet ? (
                    <>
                      <CheckCircle2 className="w-8 h-8 text-blue-600" />
                      <div className="flex flex-col items-center gap-1 w-full max-w-full px-2">
                        <span className="text-sm font-semibold text-blue-700 break-words text-center w-full max-w-full">
                          {attendanceSheet.name}
                        </span>
                        <span className="text-xs text-blue-600">
                          Document selected
                        </span>
                      </div>
                    </>
                  ) : (
                    <>
                      <Upload className="w-8 h-8 text-gray-400" />
                      <span className="text-sm text-gray-600">
                        Click to upload attendance sheet (Excel, PDF, CSV)
                      </span>
                    </>
                  )}
                </label>
              </div>
                  {attendanceSheet && (
                <div className="mt-3">
                  <p className="text-xs font-medium text-gray-600 mb-2">
                    Selected Document:
                  </p>
                  <div className="flex items-start justify-between bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 p-3 rounded-lg text-sm shadow-sm hover:shadow-md transition-shadow w-full">
                    <div className="flex items-start gap-2 flex-1 min-w-0 pr-2">
                      <FileText className="w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5" />
                      <span className="text-gray-800 font-medium break-words break-all">{attendanceSheet.name}</span>
                    </div>
                    <div className="flex items-center gap-1 flex-shrink-0 ml-2">
                      {canPreviewFile(attendanceSheet) && (
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          className="h-7 w-7 p-0 hover:bg-blue-100 hover:text-blue-700"
                          onClick={() => handlePreviewFile(attendanceSheet)}
                          title="Preview file"
                        >
                          <Eye className="w-3.5 h-3.5" />
                        </Button>
                      )}
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        className="h-7 w-7 p-0 hover:bg-green-100 hover:text-green-700"
                        onClick={() => handleDownloadFile(attendanceSheet)}
                        title="Download file"
                      >
                        <Download className="w-3.5 h-3.5" />
                      </Button>
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        className="h-7 w-7 p-0 hover:bg-red-100 hover:text-red-700"
                        onClick={() => {
                          setAttendanceSheet(null);
                          if (attendanceInputRef.current) attendanceInputRef.current.value = '';
                        }}
                        title="Remove document"
                      >
                        <X className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Completion Description */}
          <div className="space-y-2">
            <Label className="text-base font-semibold flex items-center gap-2" htmlFor="completionDescription">
              Brief Description of Completion *
            </Label>
            <Textarea
              id="completionDescription"
              placeholder="Provide a brief description of the completed activity, including key highlights, outcomes, challenges faced, and any relevant observations..."
              value={completionDescription}
              onChange={(e) => setCompletionDescription(e.target.value)}
              className="min-h-[120px]"
            />
            <p className="text-xs text-gray-500">{completionDescription.length} characters</p>
          </div>

          {/* Warning Message */}
          {!isFormValid && (
            <div className="bg-amber-50 border border-amber-200 rounded-lg p-4 flex items-start gap-3">
              <CircleAlert className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-amber-800">
                <p className="font-semibold mb-1">Missing Required Information</p>
                <p>
                  Please ensure completion date, at least one document/photo, and description are provided before submitting.
                </p>
              </div>
            </div>
          )}
        </div>

        <DialogFooter className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
          <Button
            variant="outline"
            onClick={handleClose}
            disabled={submitting}
            className="border-2"
          >
            Cancel
          </Button>
          <Button
            onClick={handleSubmit}
            disabled={submitting || !isFormValid}
            className="bg-[#2d4a3e] hover:bg-[#1f3329] text-white disabled:bg-gray-300 disabled:text-gray-500"
          >
            {submitting ? 'Submitting...' : 'Submit Documents'}
          </Button>
        </DialogFooter>
      </DialogContent>

      {/* File Preview Modal - Matching DocumentsTab style */}
      {previewFile && (
        <Dialog 
          open={!!previewFile} 
          onOpenChange={() => {
            if (previewFile?.url) {
              URL.revokeObjectURL(previewFile.url);
            }
            setPreviewFile(null);
          }}
        >
          <DialogContent className="file-preview-dialog p-3 sm:p-6">
            <div className="file-preview-content">
              <DialogHeader className="pb-4 flex-shrink-0 pr-8">
                <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                  <div className="flex items-center gap-3 flex-1 min-w-0">
                    <Eye className="w-5 h-5 text-blue-600 flex-shrink-0" />
                    <div className="flex-1 min-w-0">
                      <DialogTitle className="text-base sm:text-lg font-bold text-gray-900 truncate pr-2">
                        {previewFile.file.name}
                      </DialogTitle>
                      <p className="text-xs sm:text-sm text-gray-500">
                        {previewFile.file.type || 'Unknown type'} • {(previewFile.file.size / 1024).toFixed(1)} KB
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center gap-2 flex-wrap mr-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleDownloadFile(previewFile.file)}
                      className="gap-2 h-9"
                    >
                      <Download className="h-4 w-4" />
                      <span className="hidden sm:inline">Download</span>
                    </Button>
                  </div>
                </div>
              </DialogHeader>

              <div className="file-preview-body bg-gray-100 rounded-lg p-2 sm:p-4">
                {previewFile.file.type?.includes('image') ? (
                  <div className="flex items-center justify-center h-full">
                    <img
                      src={previewFile.url}
                      alt={previewFile.file.name}
                      style={{
                        maxWidth: '100%',
                        maxHeight: '100%',
                        objectFit: 'contain'
                      }}
                      className="rounded-lg shadow-lg"
                    />
                  </div>
                ) : previewFile.file.type?.includes('pdf') || previewFile.file.name.toLowerCase().endsWith('.pdf') ? (
                  <div className="w-full h-full flex items-center justify-center">
                    <iframe
                      src={previewFile.url}
                      className="w-full h-full rounded-lg border-0"
                      title={previewFile.file.name}
                      style={{ 
                        minHeight: '70vh',
                        height: '100%'
                      }}
                    />
                  </div>
                ) : (
                  <div className="flex flex-col items-center justify-center h-full text-center">
                    <div className="w-20 h-20 bg-gray-200 rounded-full flex items-center justify-center mb-4">
                      <Eye className="w-10 h-10 text-gray-400" />
                    </div>
                    <h3 className="text-lg font-semibold text-gray-900 mb-2">Preview Not Available</h3>
                    <p className="text-sm text-gray-600 mb-6">
                      This file type cannot be previewed. Please download to view.
                    </p>
                    <Button 
                      onClick={() => handleDownloadFile(previewFile.file)} 
                      className="gap-2"
                    >
                      <Download className="h-4 w-4" />
                      Download {previewFile.file.name}
                    </Button>
                  </div>
                )}
              </div>
            </div>
          </DialogContent>
        </Dialog>
      )}
    </Dialog>
  );
}
