/**
 * DealerProposalSubmissionModal Component
 * Modal for Step 1: Dealer Proposal Submission
 * Allows dealers to upload proposal documents, provide cost breakdown, timeline, and comments
 */

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 { HsnSacSelector } from "@/components/common/HsnSacSelector";
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { CustomDatePicker } from '@/components/ui/date-picker';
import { Upload, Plus, Minus, X, Calendar, IndianRupee, CircleAlert, CheckCircle2, FileText, Eye, Download } from 'lucide-react';
import { toast } from 'sonner';
import { handleSecurityError } from '@/utils/securityToast';
import { DocumentCard } from '@/components/workflow/DocumentUpload/DocumentCard';
import { FilePreview } from '@/components/common/FilePreview/FilePreview';
import { getDocumentPreviewUrl, downloadDocument } from '@/services/workflowApi';
import '@/components/common/FilePreview/FilePreview.css';
import './DealerProposalModal.css';
import { validateHSNSAC } from '@/utils/validationUtils';
import { getStateCodeFromGSTIN, getActiveTaxComponents } from '@/utils/gstUtils';

interface CostItem {
  id: string;
  description: string;
  amount: number;
  gstRate: number;
  gstAmt: number;
  quantity: number;
  hsnCode: string;
  cgstRate: number;
  cgstAmt: number;
  sgstRate: number;
  sgstAmt: number;
  igstRate: number;
  igstAmt: number;
  utgstRate: number;
  utgstAmt: number;
  cessRate: number;
  cessAmt: number;
  totalAmt: number;
  isService: boolean;
  isOriginal?: boolean; // Flag to identify items from previous iterations
}

interface DealerProposalSubmissionModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSubmit: (data: {
    proposalDocument: File | null;
    costBreakup: CostItem[];
    totalEstimatedBudget: number;
    expectedCompletionDate: string;
    timelineMode: 'date' | 'days';
    expectedCompletionDays: number;
    otherDocuments: File[];
    dealerComments: string;
  }) => Promise<void>;
  dealerName?: string;
  dealerGSTIN?: string;
  activityName?: string;
  requestId?: string;
  previousProposalData?: any;
  defaultGstRate?: number;
  documentPolicy: {
    maxFileSizeMB: number;
    allowedFileTypes: string[];
  };
  taxationType?: string | null;
  totalBlockedAmount?: number;
}

export function DealerProposalSubmissionModal({
  isOpen,
  onClose,
  onSubmit,
  dealerName = 'Jaipur Royal Enfield',
  dealerGSTIN,
  activityName = 'Activity',
  requestId: _requestId,
  previousProposalData,
  defaultGstRate = 18,
  documentPolicy,
  taxationType,
  totalBlockedAmount = 0,
}: DealerProposalSubmissionModalProps) {
  const [proposalDocument, setProposalDocument] = useState<File | null>(null);

  // Determine active tax components based on dealer GSTIN
  const taxConfig = useMemo(() => {
    const stateCode = getStateCodeFromGSTIN(dealerGSTIN);
    return getActiveTaxComponents(stateCode);
  }, [dealerGSTIN]);

  const isNonGst = useMemo(() => {
    return taxationType === 'Non GST' || taxationType === 'Non-GST';
  }, [taxationType]);

  const [costItems, setCostItems] = useState<CostItem[]>([
    {
      id: '1',
      description: '',
      amount: 0,
      gstRate: defaultGstRate || 0,
      gstAmt: 0,
      quantity: 1,
      hsnCode: '',
      isService: false,
      cgstRate: 0,
      cgstAmt: 0,
      sgstRate: 0,
      sgstAmt: 0,
      igstRate: 0,
      igstAmt: 0,
      utgstRate: 0,
      utgstAmt: 0,
      cessRate: 0,
      cessAmt: 0,
      totalAmt: 0
    },
  ]);

  // GST Calculation Helper
  const calculateGST = (amount: number, rates: { cgstRate: number; sgstRate: number; igstRate: number; utgstRate: number }, quantity: number = 1) => {
    const baseTotal = amount * quantity;
    const cgstAmt = (baseTotal * (rates.cgstRate || 0)) / 100;
    const sgstAmt = (baseTotal * (rates.sgstRate || 0)) / 100;
    const utgstAmt = (baseTotal * (rates.utgstRate || 0)) / 100;
    const igstAmt = (baseTotal * (rates.igstRate || 0)) / 100;
    const gstAmt = cgstAmt + sgstAmt + utgstAmt + igstAmt;
    const totalAmt = baseTotal + gstAmt;

    return {
      cgstRate: rates.cgstRate,
      cgstAmt,
      sgstRate: rates.sgstRate,
      sgstAmt,
      utgstRate: rates.utgstRate,
      utgstAmt,
      igstRate: rates.igstRate,
      igstAmt,
      gstAmt,
      gstRate: (rates.cgstRate || 0) + (rates.sgstRate || 0) + (rates.utgstRate || 0) + (rates.igstRate || 0),
      totalAmt
    };
  };
  const [timelineMode, setTimelineMode] = useState<'date' | 'days'>('date');
  const [expectedCompletionDate, setExpectedCompletionDate] = useState('');
  const [numberOfDays, setNumberOfDays] = useState('');
  const [otherDocuments, setOtherDocuments] = useState<File[]>([]);
  const [dealerComments, setDealerComments] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [previewDoc, setPreviewDoc] = useState<{
    fileName: string;
    fileType: string;
    documentId: string;
    fileUrl?: string;
    fileSize?: number;
  } | null>(null);
  const [showPreviousProposal, setShowPreviousProposal] = useState(false);

  const proposalDocInputRef = useRef<HTMLInputElement>(null);
  const otherDocsInputRef = useRef<HTMLInputElement>(null);

  // Helper function to check if file can be previewed
  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);
  };

  const canPreviewFile = (file: File): boolean => {
    return canPreview(file.name);
  };

  // Cleanup object URLs when component unmounts or file changes
  useEffect(() => {
    return () => {
      if (previewDoc?.fileUrl && previewDoc.fileUrl.startsWith('blob:')) {
        URL.revokeObjectURL(previewDoc.fileUrl);
      }
    };
  }, [previewDoc]);

  // Handle manual file preview (for local files)
  const handlePreviewFile = (file: File) => {
    if (!canPreviewFile(file)) {
      toast.error('Preview is only available for images and PDF files');
      return;
    }

    // Cleanup previous preview URL if it was a blob
    if (previewDoc?.fileUrl && previewDoc.fileUrl.startsWith('blob:')) {
      URL.revokeObjectURL(previewDoc.fileUrl);
    }

    // Create blob URL for local file
    const url = URL.createObjectURL(file);
    setPreviewDoc({
      fileName: file.name,
      fileType: file.type,
      documentId: '',
      fileUrl: url,
      fileSize: file.size
    });
  };

  // Handle preview for existing Documents (with storageUrl/documentId)
  const handlePreviewExisting = (doc: any) => {
    const fileName = doc.originalFileName || doc.fileName || doc.name || 'Document';
    const documentId = doc.documentId || doc.id || '';
    const fileType = fileName.toLowerCase().endsWith('.pdf') ? 'application/pdf' : 'image/jpeg';

    let fileUrl = '';
    if (documentId) {
      fileUrl = getDocumentPreviewUrl(documentId);
    } else {
      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
    });
  };

  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);
  };

  // Pre-populate with previous proposal data if available
  useEffect(() => {
    if (isOpen && previousProposalData) {
      const isDeltaFlow = totalBlockedAmount > 0;
      if (previousProposalData.costItems && previousProposalData.costItems.length > 0) {
        const mappedItems: CostItem[] = previousProposalData.costItems.map((item: any, index: number) => ({
          id: `original-${index}`,
          description: item.itemDescription || item.description || '',
          amount: Number(item.amount) || 0,
          quantity: Number(item.quantity) || 1,
          hsnCode: item.hsnCode || '',
          isService: !!item.isService,
          gstRate: Number(item.gstRate) || defaultGstRate,
          cgstRate: Number(item.cgstRate) || 0,
          sgstRate: Number(item.sgstRate) || 0,
          utgstRate: Number(item.utgstRate) || 0,
          igstRate: Number(item.igstRate) || 0,
          gstAmt: Number(item.gstAmt) || 0,
          cgstAmt: Number(item.cgstAmt) || 0,
          sgstAmt: Number(item.sgstAmt) || 0,
          utgstAmt: Number(item.utgstAmt) || 0,
          igstAmt: Number(item.igstAmt) || 0,
          cessRate: Number(item.cessRate) || 0,
          cessAmt: Number(item.cessAmt) || 0,
          totalAmt: Number(item.totalAmt) || 0,
          isOriginal: isDeltaFlow // Only lock as original if budget is already being blocked
        }));
        setCostItems(mappedItems);
      }

      if (previousProposalData.expectedCompletionDate) {
        setExpectedCompletionDate(previousProposalData.expectedCompletionDate.split('T')[0]);
        setTimelineMode('date');
      }

      // We DON'T pre-populate comments to force dealer to explain the re-quotation
      // setDealerComments(previousProposalData.comments || '');
    } else if (isOpen && !previousProposalData) {
      // Default state for new proposals
      setCostItems([{
        id: '1',
        description: '',
        amount: 0,
        gstRate: defaultGstRate || 0,
        gstAmt: 0,
        quantity: 1,
        hsnCode: '',
        isService: false,
        cgstRate: 0,
        cgstAmt: 0,
        sgstRate: 0,
        sgstAmt: 0,
        igstRate: 0,
        igstAmt: 0,
        utgstRate: 0,
        utgstAmt: 0,
        cessRate: 0,
        cessAmt: 0,
        totalAmt: 0
      }]);
      setExpectedCompletionDate('');
      setDealerComments('');
    }
  }, [isOpen, previousProposalData, defaultGstRate, totalBlockedAmount]);

  // Calculate total estimated budget (inclusive of GST)
  const totalBudget = useMemo(() => {
    return costItems.reduce((sum, item) => sum + (item.totalAmt || item.amount || 0), 0);
  }, [costItems]);

  // Check if all required fields are filled
  const isFormValid = useMemo(() => {
    const hasProposalDoc = proposalDocument !== null;
    const hasValidCostItems = costItems.length > 0 &&
      costItems.every(item => item.description.trim() !== '' && item.amount > 0);
    const hasTimeline = timelineMode === 'date'
      ? expectedCompletionDate !== ''
      : numberOfDays !== '' && parseInt(numberOfDays) > 0;
    const hasValidComments = dealerComments.trim().length > 0;

    const hasHSNSACErrors = isNonGst ? false : costItems.some(item => {
      const { isValid } = validateHSNSAC(item.hsnCode, item.isService);
      return !isValid;
    });

    return hasProposalDoc && hasValidCostItems && hasTimeline && hasValidComments && !hasHSNSACErrors;
  }, [proposalDocument, costItems, timelineMode, expectedCompletionDate, numberOfDays, dealerComments, isNonGst]);

  const handleProposalDocChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      // 1. Check file size
      const maxSizeBytes = documentPolicy.maxFileSizeMB * 1024 * 1024;
      if (file.size > maxSizeBytes) {
        toast.error(`File size exceeds the maximum allowed size of ${documentPolicy.maxFileSizeMB}MB. Current size: ${(file.size / (1024 * 1024)).toFixed(2)}MB`);
        if (proposalDocInputRef.current) proposalDocInputRef.current.value = '';
        return;
      }

      // 2. Validate file type (User requested: Keep strictly to pdf, doc, docx + Intersection with system policy)
      const hardcodedAllowed = ['.pdf', '.doc', '.docx'];
      const fileExtension = '.' + file.name.split('.').pop()?.toLowerCase();
      const simpleExt = file.name.split('.').pop()?.toLowerCase() || '';

      if (!hardcodedAllowed.includes(fileExtension) || !documentPolicy.allowedFileTypes.includes(simpleExt)) {
        toast.error('Please upload a valid PDF, DOC, or DOCX file as per system policy');
        if (proposalDocInputRef.current) proposalDocInputRef.current.value = '';
        return;
      }

      setProposalDocument(file);
    }
  };

  const handleOtherDocsChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    const validFiles: File[] = [];
    const maxSizeBytes = documentPolicy.maxFileSizeMB * 1024 * 1024;

    files.forEach(file => {
      // 1. Check file size
      if (file.size > maxSizeBytes) {
        toast.error(`"${file.name}" exceeds ${documentPolicy.maxFileSizeMB}MB limit and was not added.`);
        return;
      }

      // 2. Check file type
      const fileExtension = file.name.split('.').pop()?.toLowerCase() || '';
      if (!documentPolicy.allowedFileTypes.includes(fileExtension)) {
        toast.error(`"${file.name}" has an unsupported file type and was not added.`);
        return;
      }

      validFiles.push(file);
    });

    if (validFiles.length > 0) {
      setOtherDocuments(prev => [...prev, ...validFiles]);
    }

    // Reset input so searching the same file again triggers change event
    if (otherDocsInputRef.current) otherDocsInputRef.current.value = '';
  };

  const handleAddCostItem = () => {
    setCostItems(prev => [
      ...prev,
      {
        id: Date.now().toString(),
        description: '',
        amount: 0,
        gstRate: defaultGstRate || 0,
        gstAmt: 0,
        quantity: 1,
        hsnCode: '',
        isService: false,
        cgstRate: 0,
        cgstAmt: 0,
        sgstRate: 0,
        sgstAmt: 0,
        igstRate: 0,
        igstAmt: 0,
        utgstRate: 0,
        utgstAmt: 0,
        cessRate: 0,
        cessAmt: 0,
        totalAmt: 0
      },
    ]);
  };

  const handleRemoveCostItem = (id: string) => {
    if (costItems.length > 1) {
      setCostItems(prev => prev.filter(item => item.id !== id));
    }
  };

  const handleCostItemChange = (id: string, field: string, value: any) => {
    setCostItems(prev =>
      prev.map(item => {
        if (item.id === id) {
          let updatedItem = { ...item, [field]: value };

          if (['amount', 'gstRate', 'cgstRate', 'sgstRate', 'utgstRate', 'igstRate'].includes(field)) {
            // Negative amount validation
            const numValue = parseFloat(value);
            if (!isNaN(numValue) && numValue < 0) {
              toast.error('Value cannot be negative');
              return item;
            }

            const amount = field === 'amount' ? parseFloat(value) || 0 : item.amount;
            const quantity = 1; // Quantity is now fixed to 1

            let cgstRate = item.cgstRate;
            let sgstRate = item.sgstRate;
            let utgstRate = item.utgstRate;
            let igstRate = item.igstRate;

            if (field === 'cgstRate') {
              if (!taxConfig.isCGST) return item;
              cgstRate = parseFloat(value) || 0;
              // If UTGST is active for this dealer, sync with it
              if (taxConfig.isUTGST) {
                utgstRate = cgstRate;
                sgstRate = 0;
              } else {
                sgstRate = cgstRate;
                utgstRate = 0;
              }
              igstRate = 0;
            } else if (field === 'sgstRate') {
              if (!taxConfig.isSGST) return item;
              sgstRate = parseFloat(value) || 0;
              cgstRate = sgstRate;
              utgstRate = 0;
              igstRate = 0;
            } else if (field === 'utgstRate') {
              if (!taxConfig.isUTGST) return item;
              utgstRate = parseFloat(value) || 0;
              cgstRate = utgstRate;
              sgstRate = 0;
              igstRate = 0;
            } else if (field === 'igstRate') {
              if (!taxConfig.isIGST) return item;
              igstRate = parseFloat(value) || 0;
              cgstRate = 0;
              sgstRate = 0;
              utgstRate = 0;
            } else if (field === 'gstRate') {
              const totalRate = parseFloat(value) || 0;
              if (taxConfig.isIGST) {
                igstRate = totalRate;
                cgstRate = 0;
                sgstRate = 0;
                utgstRate = 0;
              } else {
                cgstRate = totalRate / 2;
                if (taxConfig.isUTGST) {
                  utgstRate = totalRate / 2;
                  sgstRate = 0;
                } else {
                  sgstRate = totalRate / 2;
                  utgstRate = 0;
                }
                igstRate = 0;
              }
            }

            const calculation = calculateGST(amount, { cgstRate, sgstRate, igstRate, utgstRate }, quantity);

            return {
              ...updatedItem,
              amount,
              quantity,
              ...calculation
            };
          }

          return updatedItem;
        }
        return item;
      })
    );
  };

  const handleRemoveOtherDoc = (index: number) => {
    setOtherDocuments(prev => prev.filter((_, i) => i !== index));
  };

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

    // Check for negative amounts or invalid days
    const hasNegativeAmounts = costItems.some(item => item.amount < 0);
    if (hasNegativeAmounts) {
      toast.error('Please ensure all amounts are non-negative');
      return;
    }

    if (timelineMode === 'days' && (parseInt(numberOfDays) <= 0 || isNaN(parseInt(numberOfDays)))) {
      toast.error('Please enter a valid number of days greater than 0');
      return;
    }

    // Calculate final completion date if using days mode
    let finalCompletionDate: string = expectedCompletionDate || '';
    if (timelineMode === 'days' && numberOfDays) {
      const days = parseInt(numberOfDays);
      const date = new Date();
      date.setDate(date.getDate() + days);
      const isoString = date.toISOString();
      finalCompletionDate = isoString.split('T')[0] as string;
    }

    try {
      setSubmitting(true);
      // Validation: Alert for 0% GST on taxable items (Skip for Non-GST)
      const hasZeroGstItems = !isNonGst && costItems.some(item =>
        item.description.trim() !== '' && item.amount > 0 && (item.gstRate === 0 || !item.gstRate)
      );

      if (hasZeroGstItems) {
        const confirmZeroGst = window.confirm(
          "One or more items have 0% GST. Are you sure you want to proceed? \n\nNote: If these items are taxable, please provide a valid GST rate to ensure correct E-Invoice generation."
        );
        if (!confirmZeroGst) {
          setSubmitting(false);
          return;
        }
      }

      const isDeltaFlow = totalBlockedAmount > 0;
      const costBreakup = costItems
        .filter(item => item.description.trim() !== '' && item.amount > 0)
        .map(item => ({
          ...item,
          description: (previousProposalData && isDeltaFlow && !item.isOriginal)
            ? `[ADDITIONAL] ${item.description}`
            : item.description
        }));

      await onSubmit({
        proposalDocument,
        costBreakup,
        totalEstimatedBudget: totalBudget,
        expectedCompletionDate: finalCompletionDate,
        timelineMode,
        expectedCompletionDays: timelineMode === 'days' ? parseInt(numberOfDays) : 0,
        otherDocuments,
        dealerComments,
      });
      handleReset();
      onClose();
    } catch (error) {
      console.error('Failed to submit proposal:', error);
      if (!handleSecurityError(error)) {
        toast.error('Failed to submit proposal. Please try again.');
      }
    } finally {
      setSubmitting(false);
    }
  };

  const handleReset = () => {
    // Cleanup preview URL if exists and it's a blob
    if (previewDoc?.fileUrl && previewDoc.fileUrl.startsWith('blob:')) {
      URL.revokeObjectURL(previewDoc.fileUrl);
    }
    setPreviewDoc(null);
    setProposalDocument(null);
    setCostItems([{
      id: '1',
      description: '',
      amount: 0,
      gstRate: 0,
      gstAmt: 0,
      quantity: 1,
      hsnCode: '',
      isService: false,
      cgstRate: 0,
      cgstAmt: 0,
      sgstRate: 0,
      sgstAmt: 0,
      igstRate: 0,
      igstAmt: 0,
      utgstRate: 0,
      utgstAmt: 0,
      cessRate: 0,
      cessAmt: 0,
      totalAmt: 0
    }]);
    setTimelineMode('date');
    setExpectedCompletionDate('');
    setNumberOfDays('');
    setOtherDocuments([]);
    setDealerComments('');
    if (proposalDocInputRef.current) proposalDocInputRef.current.value = '';
    if (otherDocsInputRef.current) otherDocsInputRef.current.value = '';
  };

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

  // Get minimum date (today)
  const minDate = new Date().toISOString().split('T')[0];
  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogContent className="dealer-proposal-modal overflow-hidden flex flex-col">
        <DialogHeader className="flex-shrink-0 pb-3 lg:pb-4">
          <DialogTitle className="flex items-center gap-2 text-xl lg:text-2xl flex-wrap">
            <div className="flex items-center gap-2">
              <Upload className="w-5 h-5 lg:w-6 lg:h-6 text-[--re-green]" />
              Dealer Proposal Submission
            </div>
            {taxationType && (
              <Badge className={`ml-2 border-none shadow-sm ${taxationType === 'GST' ? 'bg-emerald-600 text-white hover:bg-emerald-700' : 'bg-indigo-600 text-white hover:bg-indigo-700'}`}>
                {taxationType === 'GST' ? 'GST Claim' : 'Non-GST Claim'}
              </Badge>
            )}
          </DialogTitle>
          <DialogDescription className="text-sm lg:text-base">
            Step 1: Upload proposal and planning details
          </DialogDescription>
          <div className="space-y-1 mt-2 text-xs lg:text-sm text-gray-600">
            <div className="flex flex-wrap gap-x-4 gap-y-1">
              <div>
                <strong>Dealer:</strong> {dealerName}
              </div>
              <div>
                <strong>Activity:</strong> {activityName}
              </div>
            </div>
            <div className="mt-1">
              Please upload proposal document, provide cost breakdown, timeline, and detailed comments.
            </div>
          </div>
        </DialogHeader>

        <div className="flex-1 overflow-y-auto overflow-x-hidden min-h-0 py-3 lg:py-4">

          {/* Previous Proposal Reference Section */}
          {previousProposalData && (
            <div className="mb-6 mx-1">
              <div
                className="bg-amber-50 border border-amber-200 rounded-lg overflow-hidden cursor-pointer hover:bg-amber-100/50 transition-colors"
                onClick={() => setShowPreviousProposal(!showPreviousProposal)}
              >
                <div className="px-4 py-3 flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <FileText className="w-4 h-4 text-amber-700" />
                    <span className="text-sm font-semibold text-amber-900">Reference: Previous Proposal Details</span>
                    <Badge variant="secondary" className="bg-amber-200 text-amber-800 text-[10px]">
                      ₹{Number(previousProposalData.totalEstimatedBudget || previousProposalData.totalBudget || 0).toLocaleString('en-IN')}
                    </Badge>
                  </div>
                  <Button variant="ghost" size="sm" className="h-6 w-6 p-0 text-amber-700">
                    {showPreviousProposal ? <Minus className="w-4 h-4" /> : <Plus className="w-4 h-4" />}
                  </Button>
                </div>

                {showPreviousProposal && (
                  <div className="px-4 pb-4 border-t border-amber-200 space-y-4 bg-white/50">
                    {/* Header Info: Date & Document */}
                    <div className="flex flex-wrap gap-4 text-xs">
                      {previousProposalData.expectedCompletionDate && (
                        <div className="flex items-center gap-1.5 text-gray-700">
                          <Calendar className="w-3.5 h-3.5 text-gray-500" />
                          <span className="font-medium">Expected Completion:</span>
                          <span>{new Date(previousProposalData.expectedCompletionDate).toLocaleDateString('en-IN')}</span>
                        </div>
                      )}

                      {previousProposalData.documentUrl && (
                        <div className="flex items-center gap-1.5">
                          {canPreview(previousProposalData.documentUrl) ? (
                            <>
                              <Eye className="w-3.5 h-3.5 text-blue-500" />
                              <a
                                href={previousProposalData.documentUrl}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="text-blue-600 hover:underline font-medium flex items-center gap-1"
                              >
                                View Previous Document
                              </a>
                            </>
                          ) : (
                            <>
                              <Download className="w-3.5 h-3.5 text-blue-500" />
                              <a
                                href={previousProposalData.documentUrl}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="text-blue-600 hover:underline font-medium flex items-center gap-1"
                              >
                                Download Previous Document
                              </a>
                            </>
                          )}
                        </div>
                      )}

                      {/* Additional/Supporting Documents */}
                      {previousProposalData.otherDocuments && previousProposalData.otherDocuments.length > 0 && (
                        <div className="w-full pt-2 border-t border-amber-200/50">
                          <p className="text-[10px] font-semibold text-gray-700 mb-1.5 flex items-center gap-1">
                            <FileText className="w-3 h-3" />
                            Supporting Documents
                          </p>
                          <div className="space-y-2 max-h-[150px] overflow-y-auto">
                            {previousProposalData.otherDocuments.map((doc: any, idx: number) => (
                              <DocumentCard
                                key={idx}
                                document={{
                                  documentId: doc.documentId || doc.id || '',
                                  name: doc.originalFileName || doc.fileName || doc.name || 'Supporting Document',
                                  fileType: (doc.originalFileName || doc.fileName || doc.name || '').split('.').pop() || 'file',
                                  uploadedAt: doc.uploadedAt || new Date().toISOString()
                                }}
                                onPreview={canPreview(doc.originalFileName || doc.fileName || doc.name || '') ? () => handlePreviewExisting(doc) : undefined}
                                onDownload={async (id) => {
                                  if (id) {
                                    await downloadDocument(id);
                                  } else {
                                    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>
                      )}
                    </div>

                    {/* Previous Cost Breakup (handling both costBreakup and costItems) */}
                    {(previousProposalData.costItems || previousProposalData.costBreakup) && (previousProposalData.costItems || previousProposalData.costBreakup).length > 0 && (
                      <div className="mt-2">
                        <p className="text-xs font-semibold text-gray-700 mb-2">Previous Cost Breakdown:</p>
                        <div className="border rounded-md overflow-hidden text-xs">
                          <table className="w-full text-left">
                            <thead className="bg-gray-50 text-gray-600">
                              <tr>
                                <th className="p-2 font-medium">Description</th>
                                <th className="p-2 font-medium text-right">Amount</th>
                              </tr>
                            </thead>
                            <tbody className="divide-y">
                              {(previousProposalData.costItems || previousProposalData.costBreakup).map((item: any, idx: number) => (
                                <tr key={idx} className="bg-white">
                                  <td className="p-2 text-gray-800">{item.description}</td>
                                  <td className="p-2 text-right text-gray-800 font-medium">
                                    ₹{Number(item.amount).toLocaleString('en-IN')}
                                  </td>
                                </tr>
                              ))}
                              <tr className="bg-gray-50 font-bold">
                                <td colSpan={1} className="p-2 text-gray-900">Total</td>
                                <td className="p-2 text-right text-gray-900">
                                  ₹{Number(previousProposalData.totalEstimatedBudget || previousProposalData.totalBudget || 0).toLocaleString('en-IN')}
                                </td>
                              </tr>
                            </tbody>
                          </table>
                        </div>
                      </div>
                    )}

                    {/* Previous Comments */}
                    {(previousProposalData.comments || previousProposalData.dealerComments) && (
                      <div>
                        <p className="text-xs font-semibold text-gray-700 mb-1">Previous Comments:</p>
                        <div className="bg-white border rounded p-2 text-xs text-gray-600 italic">
                          "{previousProposalData.comments || previousProposalData.dealerComments}"
                        </div>
                      </div>
                    )}
                  </div>
                )}
              </div>
            </div>
          )}

          <div className="space-y-6 lg:space-y-0 lg:grid lg:grid-cols-2 lg:gap-x-8 lg:gap-y-6 lg:items-start">
            {/* 1. Proposal Document - Column 1 */}
            <div className="space-y-2 lg:space-y-2">
              <div className="flex items-center gap-2">
                <h3 className="font-semibold text-base lg:text-lg">Proposal Document</h3>
                <Badge variant="outline" className="text-xs border-red-500 text-red-700 bg-red-50 font-medium">Required</Badge>
              </div>
              <div
                className={`border-2 border-dashed rounded-lg p-3 lg:p-4 transition-all duration-200 ${proposalDocument
                  ? 'border-green-500 bg-green-50'
                  : 'border-gray-300 bg-white'
                  }`}
              >
                <input
                  ref={proposalDocInputRef}
                  type="file"
                  accept={['.pdf', '.doc', '.docx'].filter(ext => documentPolicy.allowedFileTypes.includes(ext.replace('.', ''))).join(',')}
                  className="hidden"
                  id="proposalDoc"
                  onChange={handleProposalDocChange}
                />
                <label htmlFor="proposalDoc" className="cursor-pointer flex flex-col items-center gap-2">
                  {proposalDocument ? (
                    <div className="flex flex-col items-center gap-2 w-full text-center">
                      <CheckCircle2 className="w-8 h-8 text-green-600" />
                      <span className="text-sm font-semibold text-green-700 truncate w-full px-2">{proposalDocument.name}</span>
                      <div className="flex gap-2">
                        {canPreviewFile(proposalDocument) && (
                          <Button type="button" variant="outline" size="sm" onClick={() => handlePreviewFile(proposalDocument)} className="h-7 text-[10px]">Preview</Button>
                        )}
                        <Button type="button" variant="outline" size="sm" onClick={() => handleDownloadFile(proposalDocument)} className="h-7 text-[10px]">Download</Button>
                      </div>
                    </div>
                  ) : (
                    <>
                      <Upload className="w-8 h-8 text-gray-400" />
                      <span className="text-sm text-gray-600">Upload Proposal (PDF, DOC)</span>
                    </>
                  )}
                </label>
              </div>
            </div>

            {/* 2. Timeline for Closure - Column 2 */}
            <div className="space-y-2 lg:space-y-2">
              <div className="flex items-center gap-2">
                <h3 className="font-semibold text-base lg:text-lg">Timeline for Closure</h3>
                <Badge variant="outline" className="text-xs border-red-500 text-red-700 bg-red-50 font-medium">Required</Badge>
              </div>
              <div className="space-y-3">
                <div className="flex gap-2">
                  <Button
                    type="button"
                    onClick={() => setTimelineMode('date')}
                    className={timelineMode === 'date' ? 'bg-[#2d4a3e] text-white flex-1' : 'border flex-1'}
                    size="sm"
                  >
                    Date
                  </Button>
                  <Button
                    type="button"
                    onClick={() => setTimelineMode('days')}
                    className={timelineMode === 'days' ? 'bg-[#2d4a3e] text-white flex-1' : 'border flex-1'}
                    size="sm"
                  >
                    Days
                  </Button>
                </div>
                {timelineMode === 'date' ? (
                  <CustomDatePicker
                    value={expectedCompletionDate || null}
                    onChange={(date) => setExpectedCompletionDate(date || '')}
                    minDate={minDate}
                    placeholderText="dd/mm/yyyy"
                    className="w-full"
                  />
                ) : (
                  <Input
                    type="number"
                    placeholder="Enter number of days"
                    min="1"
                    value={numberOfDays}
                    onChange={(e) => setNumberOfDays(e.target.value)}
                    className="h-10 w-full"
                  />
                )}
              </div>
            </div>

            {/* 3. Cost Breakup Section - Full Width (Row 2) */}
            <div className="lg:col-span-2 space-y-3 py-4 border-y border-gray-100 mt-2">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <h3 className="font-semibold text-lg text-[#2d4a3e]">Cost Breakup</h3>
                  <Badge variant="outline" className="text-xs border-[#2d4a3e] text-[#2d4a3e] bg-green-50 font-medium">Required</Badge>
                </div>
                {!isNonGst && (
                  <div className="text-[10px] text-gray-500 italic mt-0.5">
                    Tax fields are automatically toggled based on the dealer's state (Inter-state vs Intra-state).
                  </div>
                )}
                <Button
                  type="button"
                  onClick={handleAddCostItem}
                  className="bg-[#2d4a3e] hover:bg-[#1f3329] text-white"
                  size="sm"
                >
                  <Plus className="w-4 h-4 mr-1" />
                  Add Item
                </Button>
              </div>

              <div className="space-y-4 max-h-[400px] overflow-y-auto pr-1">
                {costItems.map((item) => (
                  <div key={item.id} className="p-4 border rounded-xl bg-gray-50/50 hover:bg-gray-50 transition-colors shadow-sm relative group">
                    <div className="flex flex-col gap-4">
                      {/* Row 1: Description and Close */}
                      <div className="flex gap-3 items-start">
                        <div className={`${isNonGst ? 'flex-[3]' : 'flex-1'}`}>
                          <div className="flex items-center justify-between mb-1">
                            <Label className="text-[10px] uppercase text-gray-500 font-bold">Item Description</Label>
                            {item.isOriginal ? (
                              <Badge className="text-[9px] h-4 bg-gray-200 text-gray-700 hover:bg-gray-200 border-none">ORIGINAL</Badge>
                            ) : (previousProposalData && totalBlockedAmount > 0) ? (
                              <Badge className="text-[9px] h-4 bg-amber-100 text-amber-700 hover:bg-amber-100 border-none">ADDITIONAL</Badge>
                            ) : null}
                          </div>
                          <Input
                            placeholder="e.g., Venue branding, Logistics, etc."
                            value={item.description}
                            onChange={(e) => handleCostItemChange(item.id, 'description', e.target.value)}
                            className={`w-full bg-white shadow-sm ${item.isOriginal ? 'bg-gray-100 cursor-not-allowed' : ''}`}
                            disabled={item.isOriginal}
                          />
                        </div>
                        {isNonGst && (
                          <div className="flex-1 min-w-[140px]">
                            <Label className="text-[10px] uppercase text-gray-500 font-bold mb-1 block">Amount</Label>
                            <div className="relative">
                              <IndianRupee className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400" />
                              <Input
                                type="number"
                                value={item.amount || ''}
                                onChange={(e) => handleCostItemChange(item.id, 'amount', e.target.value)}
                                className={`pl-8 bg-white shadow-sm ${item.isOriginal ? 'bg-gray-100 cursor-not-allowed' : ''}`}
                                disabled={item.isOriginal}
                              />
                            </div>
                          </div>
                        )}
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          className="mt-6 hover:bg-red-50 hover:text-red-600 h-9 w-9 p-0 rounded-full"
                          onClick={() => handleRemoveCostItem(item.id)}
                          disabled={costItems.length === 1 || item.isOriginal}
                        >
                          <X className="w-4 h-4" />
                        </Button>
                      </div>

                      {!isNonGst && (
                        <div className="flex flex-wrap gap-x-4 gap-y-3 items-start">
                          <div className="flex-1 min-w-[140px]">
                            <Label className="text-[10px] uppercase text-gray-500 font-bold mb-1 block">Amount (Base)</Label>
                            <div className="relative">
                              <IndianRupee className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400" />
                              <Input
                                type="number"
                                value={item.amount || ''}
                                onChange={(e) => handleCostItemChange(item.id, 'amount', e.target.value)}
                                className={`pl-8 bg-white shadow-sm ${item.isOriginal ? 'bg-gray-100 cursor-not-allowed' : ''}`}
                                disabled={item.isOriginal}
                              />
                            </div>
                          </div>
                          <div className="w-28 sm:w-32 relative pb-5">
                            <Label className="text-[10px] uppercase text-gray-500 font-bold mb-1 block">HSN/SAC Code</Label>
                            <HsnSacSelector
                              value={item.hsnCode || ''}
                              onChange={(value) => handleCostItemChange(item.id, 'hsnCode', value)}
                              type={item.isService ? 'SAC' : 'HSN'}
                              disabled={item.isOriginal}
                              className={!validateHSNSAC(item.hsnCode, item.isService).isValid ? 'border-red-500' : ''}
                              placeholder={item.isService ? 'Select SAC' : 'Select HSN'}
                            />
                            {!validateHSNSAC(item.hsnCode, item.isService).isValid && (
                              <span className="text-[10px] text-red-500 absolute left-0 bottom-0 block leading-tight">
                                {validateHSNSAC(item.hsnCode, item.isService).message}
                              </span>
                            )}
                          </div>
                          <div className="w-28 sm:w-32">
                            <Label className="text-[10px] uppercase text-gray-500 font-bold mb-1 block">Type</Label>
                            <select
                              value={item.isService ? 'SAC' : 'HSN'}
                              onChange={(e) => handleCostItemChange(item.id, 'isService', e.target.value === 'SAC')}
                              className={`flex h-10 w-full rounded-md border border-input bg-white px-3 py-2 text-sm shadow-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-[#2d4a3e] ${item.isOriginal ? 'bg-gray-100 cursor-not-allowed' : ''}`}
                              disabled={item.isOriginal}
                            >
                              <option value="HSN">HSN (Goods)</option>
                              <option value="SAC">SAC (Service)</option>
                            </select>
                          </div>
                          <div className="w-16">
                            <Label className="text-[10px] uppercase text-gray-500 font-bold mb-1 block">CGST %</Label>
                            <Input
                              type="number"
                              value={item.cgstRate || ''}
                              onChange={(e) => handleCostItemChange(item.id, 'cgstRate', e.target.value)}
                              disabled={!taxConfig.isCGST}
                              className="bg-white shadow-sm text-center px-1 disabled:bg-gray-100 disabled:text-gray-400"
                            />
                          </div>
                          <div className="w-16">
                            <Label className="text-[10px] uppercase text-gray-500 font-bold mb-1 block">SGST %</Label>
                            <Input
                              type="number"
                              value={item.sgstRate || ''}
                              onChange={(e) => handleCostItemChange(item.id, 'sgstRate', e.target.value)}
                              disabled={!taxConfig.isSGST}
                              className="bg-white shadow-sm text-center px-1 disabled:bg-gray-100 disabled:text-gray-400"
                            />
                          </div>
                          <div className="w-16">
                            <Label className="text-[10px] uppercase text-gray-500 font-bold mb-1 block">UTGST %</Label>
                            <Input
                              type="number"
                              value={item.utgstRate || ''}
                              onChange={(e) => handleCostItemChange(item.id, 'utgstRate', e.target.value)}
                              disabled={!taxConfig.isUTGST}
                              className="bg-white shadow-sm text-center px-1 disabled:bg-gray-100 disabled:text-gray-400"
                            />
                          </div>
                          <div className="w-16">
                            <Label className="text-[10px] uppercase text-gray-500 font-bold mb-1 block">IGST %</Label>
                            <Input
                              type="number"
                              value={item.igstRate || ''}
                              onChange={(e) => handleCostItemChange(item.id, 'igstRate', e.target.value)}
                              disabled={!taxConfig.isIGST}
                              className="bg-white shadow-sm text-center px-1 disabled:bg-gray-100 disabled:text-gray-400"
                            />
                          </div>
                        </div>
                      )}

                      {!isNonGst && (
                        <div className="flex flex-wrap gap-4 pt-3 border-t border-dashed items-center justify-between text-xs">
                          <div className="flex gap-4 text-gray-500 font-medium">
                            <span>CGST: <span className="text-gray-900">₹{item.cgstAmt.toLocaleString('en-IN', { minimumFractionDigits: 1 })}</span></span>
                            {item.sgstAmt > 0 && <span>SGST: <span className="text-gray-900">₹{item.sgstAmt.toLocaleString('en-IN', { minimumFractionDigits: 1 })}</span></span>}
                            {item.utgstAmt > 0 && <span>UTGST: <span className="text-gray-900">₹{item.utgstAmt.toLocaleString('en-IN', { minimumFractionDigits: 1 })}</span></span>}
                            <span>IGST: <span className="text-gray-900">₹{item.igstAmt.toLocaleString('en-IN', { minimumFractionDigits: 1 })}</span></span>
                          </div>
                          <div className="flex gap-4 items-center">
                            <span className="text-gray-500">GST Total: <span className="text-gray-900 font-semibold">₹{item.gstAmt.toLocaleString('en-IN', { minimumFractionDigits: 1 })}</span></span>
                            <span className="text-sm font-bold text-[#2d4a3e] bg-green-50 px-3 py-1 rounded-lg">Item Total: ₹{item.totalAmt.toLocaleString('en-IN', { minimumFractionDigits: 1 })}</span>
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                ))}
              </div>

              {/* Total Budget Card */}
              <div className="bg-[#2d4a3e] rounded-xl p-5 text-white flex items-center justify-between shadow-lg">
                <div className="flex items-center gap-3">
                  <div className="p-2 bg-white/20 rounded-lg">
                    <IndianRupee className="w-6 h-6" />
                  </div>
                  <div>
                    <p className="text-xs text-white/70 uppercase font-bold tracking-wider">Estimated Total Budget</p>
                    {!isNonGst && <p className="text-sm text-white/90">Inclusive of all applicable taxes</p>}
                  </div>
                </div>
                <div className="text-3xl font-bold border-l border-white/20 pl-6">
                  ₹{totalBudget.toLocaleString('en-IN', { minimumFractionDigits: 2 })}
                </div>
              </div>
            </div>

            {/* 4. Other Supporting Docs - Column 1 */}
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <h3 className="font-semibold text-base lg:text-lg">Other Documents</h3>
                <Badge variant="outline" className="text-xs border-gray-300 text-gray-500 bg-gray-50 font-medium">Optional</Badge>
              </div>
              <div
                className={`border-2 border-dashed rounded-lg p-3 lg:p-4 transition-all duration-200 ${otherDocuments.length > 0 ? 'border-blue-500 bg-blue-50' : 'border-gray-300 bg-white'}`}
              >
                <input
                  ref={otherDocsInputRef}
                  type="file"
                  multiple
                  accept={documentPolicy.allowedFileTypes.map(ext => `.${ext}`).join(',')}
                  className="hidden"
                  id="otherDocs"
                  onChange={handleOtherDocsChange}
                />
                <label htmlFor="otherDocs" className="cursor-pointer flex flex-col items-center gap-2">
                  <Upload className="w-8 h-8 text-gray-400" />
                  <span className="text-sm text-gray-600">
                    {otherDocuments.length > 0 ? `${otherDocuments.length} files selected` : 'Upload supporting files'}
                  </span>
                  <span className="text-[10px] text-gray-400">Click to add documents</span>
                </label>
              </div>

              {otherDocuments.length > 0 && (
                <div className="mt-2 space-y-2 max-h-[120px] overflow-y-auto">
                  {otherDocuments.map((file, index) => (
                    <div key={index} className="flex items-center justify-between bg-blue-50 border border-blue-100 p-2 rounded-lg text-xs">
                      <div className="flex items-center gap-2 flex-1 min-w-0 pr-2">
                        <FileText className="w-3.5 h-3.5 text-blue-600 flex-shrink-0" />
                        <span className="text-gray-700 font-medium truncate">{file.name}</span>
                      </div>
                      <div className="flex items-center gap-1">
                        {canPreviewFile(file) && (
                          <Button type="button" variant="ghost" size="sm" className="h-6 w-6 p-0 hover:bg-blue-100" onClick={() => handlePreviewFile(file)}><Eye className="w-3 h-3" /></Button>
                        )}
                        <Button type="button" variant="ghost" size="sm" className="h-6 w-6 p-0 hover:bg-green-100" onClick={() => handleDownloadFile(file)}><Download className="w-3 h-3" /></Button>
                        <Button type="button" variant="ghost" size="sm" className="h-6 w-6 p-0 hover:bg-red-100 hover:text-red-600" onClick={() => handleRemoveOtherDoc(index)}><X className="w-3 h-3" /></Button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* 5. Dealer Comments - Column 2 */}
            <div className="space-y-2">
              <Label className="font-semibold text-base lg:text-lg">Dealer Comments *</Label>
              <Textarea
                placeholder="Details about execution, special requirements, etc."
                value={dealerComments}
                onChange={(e) => setDealerComments(e.target.value)}
                className="min-h-[100px] bg-white shadow-sm"
              />
            </div>
          </div>

          {/* Warning Message */}
          {!isFormValid && (
            <div className="bg-amber-50 border border-amber-200 rounded-lg p-3 lg:p-4 flex items-start gap-2 lg:gap-3 lg:col-span-2 mt-4">
              <CircleAlert className="w-4 h-4 lg:w-5 lg:h-5 text-amber-600 flex-shrink-0 mt-0.5" />
              <div className="text-xs lg:text-sm text-amber-800">
                <p className="font-semibold mb-1">Missing Required Information</p>
                <p>
                  Please ensure proposal document, cost breakup, timeline, and dealer comments are provided before submitting.
                </p>
              </div>
            </div>
          )}
        </div>

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

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