/**
 * ProcessDetailsCard Component
 * Displays process-related details: IO Number, E-Invoice, Claim Amount, and Budget Breakdowns
 * Visibility controlled by user role
 */

import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Activity, Receipt, DollarSign, Pen } from 'lucide-react';
import { format } from 'date-fns';

// Local minimal types to avoid external dependency issues
interface IODetails {
  ioNumber?: string;
  remarks?: string;
  availableBalance?: number;
  blockedAmount?: number;
  remainingBalance?: number;
  blockedByName?: string;
  blockedAt?: string;
}

interface DMSDetails {
  dmsNumber?: string;
  eInvoiceNumber?: string;
  eInvoiceDate?: string;
  remarks?: string;
  createdByName?: string;
  createdAt?: string;
  // PWC fields
  irn?: string;
  ackNo?: string;
  ackDate?: string;
  signedInvoiceUrl?: string;
  creditNoteWfmData?: any[];
}

interface ClaimAmountDetails {
  amount: number;
  lastUpdatedBy?: string;
  lastUpdatedAt?: string;
}

interface CostBreakdownItem {
  description: string;
  amount: number;
  gstAmt?: number;
  totalAmt?: number;
  hsnCode?: string;
}

interface RoleBasedVisibility {
  showIODetails: boolean;
  showDMSDetails: boolean;
  showClaimAmount: boolean;
  canEditClaimAmount: boolean;
}

interface ProcessDetailsCardProps {
  ioDetails?: IODetails;
  dmsDetails?: DMSDetails;
  claimAmount?: ClaimAmountDetails;
  estimatedBudgetBreakdown?: CostBreakdownItem[];
  closedExpensesBreakdown?: CostBreakdownItem[];
  visibility: RoleBasedVisibility;
  onEditClaimAmount?: () => void;
  className?: string;
}

export function ProcessDetailsCard({
  dmsDetails,
  claimAmount,
  estimatedBudgetBreakdown,
  closedExpensesBreakdown,
  visibility,
  onEditClaimAmount,
  className,
}: ProcessDetailsCardProps) {
  const formatCurrency = (amount?: number | null) => {
    if (amount === undefined || amount === null || Number.isNaN(amount)) {
      return '₹0.00';
    }
    return `₹${amount.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
  };

  const formatDate = (dateString?: string | null) => {
    if (!dateString) return '';
    try {
      return format(new Date(dateString), 'MMM d, yyyy, h:mm a');
    } catch {
      return dateString || '';
    }
  };

  const calculateTotal = (items?: CostBreakdownItem[]) => {
    if (!items || items.length === 0) return 0;
    return items.reduce((sum, item) => sum + (item.totalAmt ?? (item.amount + (item.gstAmt ?? 0))), 0);
  };

  const hasInvoiceDetails = Boolean(
    dmsDetails?.eInvoiceNumber ||
    dmsDetails?.ackNo ||
    dmsDetails?.eInvoiceDate ||
    dmsDetails?.dmsNumber ||
    dmsDetails?.ackDate ||
    dmsDetails?.irn ||
    dmsDetails?.signedInvoiceUrl
  );

  // Don't render if nothing to show
  const hasContent =
    (visibility.showDMSDetails && dmsDetails) ||
    (dmsDetails?.creditNoteWfmData && dmsDetails.creditNoteWfmData.length > 0) ||
    (visibility.showClaimAmount && claimAmount && claimAmount.amount !== undefined && claimAmount.amount !== null) ||
    (estimatedBudgetBreakdown && estimatedBudgetBreakdown.length > 0) ||
    (closedExpensesBreakdown && closedExpensesBreakdown.length > 0);

  if (!hasContent) {
    return null;
  }

  return (
    <Card className={`bg-gradient-to-br from-blue-50 to-purple-50 border-2 border-blue-200 ${className}`}>
      <CardHeader>
        <CardTitle className="text-base flex items-center gap-2">
          <Activity className="w-4 h-4 text-blue-600" />
          Process Details
        </CardTitle>
        <CardDescription>Workflow reference numbers</CardDescription>
      </CardHeader>
      <CardContent className="space-y-3">
        {/* E-Invoice Details */}
        {visibility.showDMSDetails && dmsDetails && hasInvoiceDetails && (
          <div className="bg-white rounded-lg p-3 border border-purple-200">
            <div className="flex items-center gap-2 mb-2">
              <Activity className="w-4 h-4 text-purple-600" />
              <Label className="text-xs font-semibold text-purple-900 uppercase tracking-wide">
                E-Invoice Details
              </Label>
            </div>

            <div className="grid grid-cols-2 gap-3 mb-2">
              {(dmsDetails.eInvoiceNumber || dmsDetails.ackNo) && (
                <div>
                  <p className="text-[10px] text-gray-500 uppercase">Invoice Number</p>
                  <p className="font-bold text-sm text-purple-700">{dmsDetails.eInvoiceNumber || dmsDetails.ackNo }</p>
                </div>
              )}
              {dmsDetails.eInvoiceDate && (
                <div>
                  <p className="text-[10px] text-gray-500 uppercase">Invoice Date</p>
                  <p className="font-semibold text-xs text-gray-700">{formatDate(dmsDetails.eInvoiceDate)}</p>
                </div>
              )}
              {dmsDetails.dmsNumber && (
                <div>
                  <p className="text-[10px] text-gray-500 uppercase">DMS Number</p>
                  <p className="font-semibold text-xs text-gray-700">{dmsDetails.dmsNumber}</p>
                </div>
              )}
              {dmsDetails.ackDate && (
                <div>
                  <p className="text-[10px] text-gray-500 uppercase">Ack Date</p>
                  <p className="font-semibold text-xs text-gray-700">{formatDate(dmsDetails.ackDate)}</p>
                </div>
              )}
              {dmsDetails.ackNo && dmsDetails.eInvoiceNumber && (
                <div>
                  <p className="text-[10px] text-gray-500 uppercase">Ack No</p>
                  <p className="font-semibold text-xs text-gray-700">{dmsDetails.ackNo}</p>
                </div>
              )}
            </div>

            {dmsDetails.irn && (
              <div className="mb-2 p-2 bg-purple-50 rounded border border-purple-100">
                <p className="text-[10px] text-purple-600 uppercase font-semibold">IRN</p>
                <p className="text-[10px] font-mono break-all text-gray-700 leading-tight">
                  {dmsDetails.irn}
                </p>
              </div>
            )}

            {dmsDetails.signedInvoiceUrl && (
              <Button
                variant="outline"
                size="sm"
                className="w-full h-8 text-xs gap-2 mb-2 border-purple-200 text-purple-700 hover:bg-purple-50"
                onClick={() => window.open(dmsDetails.signedInvoiceUrl, '_blank')}
              >
                <Receipt className="w-3.5 h-3.5" />
                View E-Invoice
              </Button>
            )}

            {dmsDetails.remarks && (
              <div className="pt-2 border-t border-purple-100">
                <p className="text-[10px] text-gray-500 uppercase mb-1">Remarks</p>
                <p className="text-xs text-gray-900">{dmsDetails.remarks}</p>
              </div>
            )}

            <div className="pt-2 border-t border-purple-100 mt-2">
              <p className="text-[10px] text-gray-500">By {dmsDetails.createdByName || 'System'}</p>
              <p className="text-[10px] text-gray-500">{formatDate(dmsDetails.createdAt)}</p>
            </div>
          </div>
        )}

        {/* Credit Note Details */}
        {dmsDetails?.creditNoteWfmData && dmsDetails.creditNoteWfmData.length > 0 && (
          <div className="bg-white rounded-lg p-3 border border-pink-200">
            <div className="flex items-center gap-2 mb-2">
              <Receipt className="w-4 h-4 text-pink-600" />
              <Label className="text-xs font-semibold text-pink-900 uppercase tracking-wide">
                Credit Note Details
              </Label>
            </div>
            <div className="space-y-2">
              {dmsDetails.creditNoteWfmData.map((cn: any, idx: number) => (
                <div key={idx} className="bg-pink-50 p-2 rounded border border-pink-100 text-[10px]">
                  <div className="flex justify-between mb-1.5 text-pink-900">
                    <span className="font-semibold break-words flex-1 pr-2 uppercase">CN No: {cn.DOC_NO || 'N/A'}</span>
                    <span className={`px-1.5 py-0.5 rounded-sm text-white font-medium self-start whitespace-nowrap ${cn.MSG_TYP === 'E' ? 'bg-red-500' : 'bg-green-500'}`}>
                      {cn.MSG_TYP === 'E' ? 'Error' : (cn.MSG_TYP === 'S' ? 'Success' : cn.MSG_TYP || 'Processed')}
                    </span>
                  </div>
                  
                  <div className="grid grid-cols-2 gap-x-4 gap-y-1 mb-1.5 text-gray-600">
                    <div className="flex justify-between">
                      <span>Txn No:</span>
                      <span className="font-medium">{cn.TRNS_UNIQ_NO || 'N/A'}</span>
                    </div>
                    {cn.TDS_AMT !== undefined &&
                      cn.TDS_AMT !== null &&
                      cn.TDS_AMT !== '' &&
                      (Number.isNaN(Number(cn.TDS_AMT)) || Number(cn.TDS_AMT) !== 0) && (
                      <div className="flex justify-between">
                        <span>TDS:</span>
                        <span className="font-medium text-red-600">
                          {Number.isNaN(Number(cn.TDS_AMT))
                            ? String(cn.TDS_AMT)
                            : formatCurrency(Number(cn.TDS_AMT))}
                        </span>
                      </div>
                    )}
                    <div className="flex justify-between col-span-2 pt-1 border-t border-pink-100">
                      <span className="font-semibold">Credit Amount:</span>
                      <span className="font-bold text-pink-700">
                        {cn.CREDITED_TOTAL_AMT !== undefined &&
                        cn.CREDITED_TOTAL_AMT !== null &&
                        cn.CREDITED_TOTAL_AMT !== ''
                          ? (Number.isNaN(Number(cn.CREDITED_TOTAL_AMT))
                            ? String(cn.CREDITED_TOTAL_AMT)
                            : formatCurrency(Number(cn.CREDITED_TOTAL_AMT)))
                          : formatCurrency(0)}
                      </span>
                    </div>
                  </div>

                  {cn.MESSAGE && (
                    <div className="text-gray-700 italic border-l-2 border-pink-200 pl-1.5 mt-1 leading-tight">
                      {cn.MESSAGE}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Claim Amount */}
        {visibility.showClaimAmount && claimAmount && (
          <div className="bg-white rounded-lg p-3 border border-green-200">
            <div className="flex items-center justify-between gap-2 mb-2">
              <div className="flex items-center gap-2">
                <DollarSign className="w-4 h-4 text-green-600" />
                <Label className="text-xs font-semibold text-green-900 uppercase tracking-wide">
                  Claim Amount
                </Label>
              </div>
              {visibility.canEditClaimAmount && onEditClaimAmount && (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={onEditClaimAmount}
                  className="h-7 px-2 text-xs border-green-300 hover:bg-green-50"
                >
                  <Pen className="w-3 h-3 mr-1 text-green-700" />
                  Edit
                </Button>
              )}
            </div>
            <p className="text-2xl font-bold text-green-700">
              {formatCurrency(claimAmount.amount)}
            </p>
            {claimAmount.lastUpdatedBy && (
              <div className="mt-2 pt-2 border-t border-green-100">
                <p className="text-xs text-gray-500">
                  Last updated by {claimAmount.lastUpdatedBy}
                </p>
                {claimAmount.lastUpdatedAt && (
                  <p className="text-xs text-gray-500">
                    {formatDate(claimAmount.lastUpdatedAt)}
                  </p>
                )}
              </div>
            )}
          </div>
        )}

        {/* Estimated Budget Breakdown */}
        {estimatedBudgetBreakdown && estimatedBudgetBreakdown.length > 0 && (
          <div className="bg-white rounded-lg p-3 border border-amber-200">
            <div className="flex items-center gap-2 mb-2">
              <Receipt className="w-4 h-4 text-amber-600" />
              <Label className="text-xs font-semibold text-amber-900 uppercase tracking-wide">
                Estimated Budget Breakdown
              </Label>
            </div>
            <div className="space-y-1.5 pt-1">
              {estimatedBudgetBreakdown.map((item, index) => (
                <div key={index} className="space-y-0.5 pb-1.5 last:pb-0">
                  <div className="flex justify-between items-center text-[10px] sm:text-xs">
                    <div className="text-gray-700 truncate mr-2 font-medium" title={item.description}>
                      {item.description}
                    </div>
                    <span className="font-bold text-gray-900 whitespace-nowrap">
                      {formatCurrency(item.totalAmt ?? (item.amount + (item.gstAmt ?? 0)))}
                    </span>
                  </div>
                  {(item.gstAmt ?? 0) > 0 && (
                    <div className="flex justify-between items-center text-[9px] text-gray-500 pl-2 italic">
                      <div className="flex gap-2">
                        <span>Base: {formatCurrency(item.amount)}</span>
                        <span>GST: {formatCurrency(item.gstAmt)}</span>
                      </div>
                      {item.hsnCode && (
                        <span>HSN/SAC: {item.hsnCode}</span>
                      )}
                    </div>
                  )}
                  {!(item.gstAmt ?? 0) && item.hsnCode && (
                    <div className="text-[9px] text-gray-500 pl-2 italic">
                      HSN/SAC: {item.hsnCode}
                    </div>
                  )}
                </div>
              ))}
              <div className="pt-2 border-t border-amber-200 flex justify-between items-center">
                <span className="font-semibold text-gray-900 text-xs">Total</span>
                <span className="font-bold text-amber-700">
                  {formatCurrency(calculateTotal(estimatedBudgetBreakdown))}
                </span>
              </div>
            </div>
          </div>
        )}

        {/* Closed Expenses Breakdown */}
        {closedExpensesBreakdown && closedExpensesBreakdown.length > 0 && (
          <div className="bg-white rounded-lg p-3 border border-indigo-200">
            <div className="flex items-center gap-2 mb-2">
              <Receipt className="w-4 h-4 text-indigo-600" />
              <Label className="text-xs font-semibold text-indigo-900 uppercase tracking-wide">
                Closed Expenses Breakdown
              </Label>
            </div>
            <div className="space-y-1.5 pt-1">
              {closedExpensesBreakdown.map((item, index) => (
                <div key={index} className="space-y-0.5 pb-1.5 last:pb-0">
                  <div className="flex justify-between items-center text-[10px] sm:text-xs">
                    <div className="text-gray-700 truncate mr-2 font-medium" title={item.description}>
                      {item.description}
                    </div>
                    <span className="font-bold text-gray-900 whitespace-nowrap">
                      {formatCurrency(item.totalAmt ?? (item.amount + (item.gstAmt ?? 0)))}
                    </span>
                  </div>
                  {(item.gstAmt ?? 0) > 0 && (
                    <div className="flex justify-between items-center text-[9px] text-gray-500 pl-2 italic">
                      <div className="flex gap-2">
                        <span>Base: {formatCurrency(item.amount)}</span>
                        <span>GST: {formatCurrency(item.gstAmt)}</span>
                      </div>
                      {item.hsnCode && (
                        <span>HSN/SAC: {item.hsnCode}</span>
                      )}
                    </div>
                  )}
                  {!(item.gstAmt ?? 0) && item.hsnCode && (
                    <div className="text-[9px] text-gray-500 pl-2 italic">
                      HSN/SAC: {item.hsnCode}
                    </div>
                  )}
                </div>
              ))}
              <div className="pt-2 border-t border-indigo-200 flex justify-between items-center">
                <span className="font-semibold text-gray-900 text-xs">Total</span>
                <span className="font-bold text-indigo-700">
                  {formatCurrency(calculateTotal(closedExpensesBreakdown))}
                </span>
              </div>
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
