import { ArrowLeft, CheckCircle2, Clock, AlertCircle, Upload, Download, Eye, ArrowRight, MessageSquare, Loader2, Ban, Undo2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { useState, useEffect, useMemo } from 'react';
import { User as UserType } from '@/lib/mock-data';
import { toast } from 'sonner';
import { API } from '@/api/API';
import { OFFBOARDING_ACTIONS } from '@/lib/offboarding-actions';
import { useNavigate } from 'react-router-dom';
import { formatDateTime } from '@/components/ui/utils';

interface ConstitutionalChangeDetailsProps {
  requestId: string;
  onBack: () => void;
  currentUser: UserType | null;
}

// Workflow stages as per the process flow (SRS 12.2.4)
const workflowStages = [
  { id: 2, name: 'ASM Review', key: 'asm-review', role: 'ASM' },
  { id: 3, name: 'ZM/RBM Review', key: 'zm-rbm-review', role: 'ZM/RBM' },

  { id: 4, name: 'ZBH Review', key: 'zbh-review', role: 'ZBH' },
  { id: 5, name: 'DD Lead Review', key: 'lead-review', role: 'DD Lead' },
  { id: 6, name: 'DD Head Review', key: 'head-review', role: 'DD Head' },
  { id: 7, name: 'NBH Approval', key: 'nbh-approval', role: 'NBH' },
  { id: 8, name: 'Legal Review', key: 'legal-review', role: 'Legal Team' },
  { id: 9, name: 'Completed', key: 'completed', role: 'System' }
];

const formatStageLabel = (label: string) =>
  label === 'ZM/RBM Review' ? 'ZM+RBM Review' : label;

const formatStageRole = (role: string) =>
  role === 'ZM/RBM' ? 'ZM+RBM' : role;

// Document requirements mapping (same as in ConstitutionalChangePage) — SRS §12.2.4 by target constitution
const documentRequirements: Record<string, number[]> = {
  'Partnership': [1, 2, 3, 4, 8, 9, 10, 16],
  'LLP': [1, 2, 3, 7, 8, 10, 11, 16],
  'Private Limited': [1, 2, 3, 5, 6, 7, 8, 10, 16],
  'Pvt Ltd': [1, 2, 3, 5, 6, 7, 8, 10, 16],
  'Proprietorship': [1, 2, 3, 10, 16]
};

/** Ad-hoc / future uploads; not part of mandatory §12.2.4 checklist. Multiple files allowed (append). */
const OTHER_DOCUMENT_DOC_NUMBER = 99;

const documentNames: Record<number, string> = {
  1: 'GST Certificate',
  2: 'Firm PAN Copy',
  3: 'Self attested KYC\'s',
  4: 'Partnership Agreement (Notarised)',
  5: 'MOA (Applicable for Only Pvt.Ltd)',
  6: 'AOA (Applicable for Only Pvt.Ltd)',
  7: 'COI (Applicable for Only Pvt.Ltd & LLP)',
  8: 'BPA - Business Purchase Agreement',
  9: 'Firm Registration Certificate (Partnership)',
  10: 'Cancelled Cheque',
  11: 'LLP Agreement (Notarised)',
  12: 'ZBH Approval',
  13: 'NBH Approval',
  14: 'RBM Approval',
  15: 'DD-Lead Approval',
  16: 'Declaration / Authorization Letter',
  [OTHER_DOCUMENT_DOC_NUMBER]: 'Other'
};


// Helper functions moved above component to avoid lint errors
const getTypeColor = (type: string) => {
  switch (type) {
    case 'Proprietorship': return 'bg-purple-100 text-purple-700 border-purple-300';
    case 'Partnership': return 'bg-blue-100 text-blue-700 border-blue-300';
    case 'LLP': return 'bg-indigo-100 text-indigo-700 border-indigo-300';
    case 'Private Limited':
    case 'Pvt Ltd': return 'bg-cyan-100 text-cyan-700 border-cyan-300';
    default: return 'bg-slate-100 text-slate-700 border-slate-300';
  }
};

const getStatusColor = (status: string) => {
  const s = String(status || '');
  if (s === 'Completed' || s === 'Verified' || s === 'APPROVED' || s === 'COMPLETED' || s === 'CREATED' || /^DOCUMENT/i.test(s)) {
    return 'bg-green-100 text-green-700 border-green-300';
  }
  if (s.includes('Revoked') || s === 'REVOKED') return 'bg-orange-100 text-orange-800 border-orange-300';
  if (s.includes('Rejected') || s === 'REJECTED') return 'bg-red-100 text-red-700 border-red-300';
  if (s === 'SENT BACK' || s.includes('Review') || s.includes('Pending') || s === 'In Progress' || s === 'Submitted') {
    return 'bg-yellow-100 text-yellow-700 border-yellow-300';
  }
  if (s === 'UPDATED') return 'bg-slate-100 text-slate-700 border-slate-300';
  return 'bg-slate-100 text-slate-700 border-slate-300';
};

/** Audit rows were stored as UPDATED for approvals; avoid treating "UPDATED" as pending via substring "update". */
const getConstitutionalHistoryPresentation = (entry: any) => {
  const action = String(entry.action || '').toUpperCase();
  const desc = String(entry.description || '').toUpperCase();
  const rem = String(entry.remarks || '').toUpperCase();
  const details = entry.details || entry.newData || {};
  const targetStage = String(details.targetStage || '').toUpperCase();
  const detailsAction = String(details.action || '').toUpperCase();

  const combined = `${action} ${desc} ${rem} ${detailsAction}`.toUpperCase();

  if (combined.includes('REJECT')) return { variant: 'danger' as const, badge: action.replace(/_/g, ' ') || 'REJECTED' };
  if (combined.includes('REVOK')) return { variant: 'danger' as const, badge: action.replace(/_/g, ' ') || 'REVOKED' };
  if (combined.includes('SENT BACK') || combined.includes('SEND BACK') || combined.includes('RECONSIDER')) {
    return { variant: 'pending' as const, badge: action.replace(/_/g, ' ') || 'SENT BACK' };
  }

  if (combined.includes('APPROV') || combined.includes('INITI') || combined.includes('CREATE') || combined.includes('VERIF') || combined.includes('UPLOAD')) {
    return { variant: 'success' as const, badge: action.replace(/_/g, ' ') || 'APPROVED' };
  }

  if (targetStage === 'COMPLETED' || combined.includes('COMPLET')) return { variant: 'success' as const, badge: 'COMPLETED' };
  if (targetStage) return { variant: 'success' as const, badge: 'APPROVED' };

  return { variant: 'neutral' as const, badge: action.replace(/_/g, ' ') || 'EVENT' };
};

const normalizeConstitutionType = (value: string) => {
  const input = String(value || '').trim().toLowerCase();
  if (!input) return '';
  if (input.includes('proprietor')) return 'Proprietorship';
  if (input.includes('partner')) return 'Partnership';
  if (input.includes('llp')) return 'LLP';
  if (input.includes('private') || input.includes('pvt')) return 'Private Limited';
  return value;
};

export function ConstitutionalChangeDetails({ requestId, onBack, currentUser }: ConstitutionalChangeDetailsProps) {
  const navigate = useNavigate();
  const [isActionDialogOpen, setIsActionDialogOpen] = useState(false);
  const [actionType, setActionType] = useState<'approve' | 'reject' | 'sendBack' | 'revoke'>('approve');
  const [comments, setComments] = useState('');
  const [isUploadDialogOpen, setIsUploadDialogOpen] = useState(false);
  const [selectedDocType, setSelectedDocType] = useState<number | null>(null);
  const [uploadFile, setUploadFile] = useState<File | null>(null);
  const [activeMainTab, setActiveMainTab] = useState('workflow');
  const [activeDocumentTab, setActiveDocumentTab] = useState('required');
  const [request, setRequest] = useState<any>(null);
  const [auditLogs, setAuditLogs] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isActionLoading, setIsActionLoading] = useState(false);
  /** Set when POST /action returns 4xx (apisauce does not throw — must check response.ok). */
  const [actionDialogError, setActionDialogError] = useState<string | null>(null);
  const [isUploadingDoc, setIsUploadingDoc] = useState(false);
  const [rejectDocDialogOpen, setRejectDocDialogOpen] = useState(false);
  const [rejectDocIndex, setRejectDocIndex] = useState<number | null>(null);
  const [rejectDocReason, setRejectDocReason] = useState('');
  const [isRejectingDoc, setIsRejectingDoc] = useState(false);

  const fetchAuditLogs = async (entityId: string) => {
    if (!entityId) return;
    try {
      const response: any = await API.getAuditLogs('constitutional_change', entityId);
      if (response.data && response.data.success) {
        setAuditLogs(response.data.data || []);
      }
    } catch (error) {
      console.error('Error fetching audit logs:', error);
    }
  };

  const fetchRequestDetails = async (opts?: { silent?: boolean }) => {
    try {
      if (!opts?.silent) setIsLoading(true);
      const response = await API.getConstitutionalChangeById(requestId) as any;
      if (response.data.success) {
        const reqData = response.data.request;
        setRequest(reqData);
        await fetchAuditLogs(reqData?.id || requestId);
      } else {
        toast.error('Failed to fetch request details');
      }
    } catch (error) {
      console.error('Fetch request details error:', error);
      toast.error('Error loading request details');
    } finally {
      if (!opts?.silent) setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchRequestDetails();
  }, [requestId]);

  const historyEntries = useMemo(() => {
    if (auditLogs.length > 0) return auditLogs;
    const tl = (request?.timeline || []) as any[];
    return tl.map((t: any, i: number) => ({
      id: `timeline-${i}`,
      action: String(t.action || 'UPDATED'),
      description: t.remarks || t.action || 'Updated',
      stage: t.stage || null,
      userName: t.user || t.userName || 'System',
      remarks: t.remarks,
      timestamp: t.timestamp || t.createdAt
    }));
  }, [auditLogs, request?.timeline]);

  /** Must run before any conditional return (Rules of Hooks). */
  const uploadDocumentTypeOptions = useMemo(() => {
    const normalized = normalizeConstitutionType(String(request?.changeType || ''));
    const base = documentRequirements[normalized] || [];
    const merged = [...base];
    if (!merged.includes(OTHER_DOCUMENT_DOC_NUMBER)) merged.push(OTHER_DOCUMENT_DOC_NUMBER);
    return merged.sort((a, b) => {
      if (a === OTHER_DOCUMENT_DOC_NUMBER) return 1;
      if (b === OTHER_DOCUMENT_DOC_NUMBER) return -1;
      return a - b;
    });
  }, [request?.changeType]);

  if (isLoading) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[400px] space-y-4">
        <Loader2 className="w-8 h-8 text-amber-600 animate-spin" />
        <p className="text-slate-600">Loading request details...</p>
      </div>
    );
  }

  if (!request) {
    return (
      <div className="bg-white rounded-lg border border-slate-200 p-8 text-center">
        <h2 className="text-slate-900 mb-2">Request Not Found</h2>
        <p className="text-slate-600 mb-4">The constitutional change request you're looking for doesn't exist.</p>
        <Button onClick={onBack}>Go Back</Button>
      </div>
    );
  }

  // Get required documents for this request (normalized mapping handles values like "LLP Conversion")
  const normalizedChangeType = normalizeConstitutionType(request.changeType);
  const requiredDocs = documentRequirements[normalizedChangeType] || [];

  const findUploadedForDocNum = (docNum: number) => {
    const docs = request.documents || [];
    const label = documentNames[docNum];
    return docs.find((d: any) => {
      const n = Number(d?.docNumber);
      if (!Number.isNaN(n) && n === docNum) return true;
      if (label && typeof d?.name === 'string' && d.name.includes(label)) return true;
      return false;
    });
  };

  const isDocTypeUploaded = (docNum: number) => {
    const u = findUploadedForDocNum(docNum);
    return !!u && String(u.status || '') !== 'Rejected';
  };

  // Calculate current stage index mapping to backend stages
  const getCurrentStageIndex = () => {
    let currentStage = request.currentStage || '';

    // For terminal states, resolve the last active stage from timeline
    if (['Rejected', 'Revoked', 'Withdrawn'].includes(request.status) && (currentStage === 'Rejected' || currentStage === 'Revoked' || !currentStage)) {
      const lastEntry = [...(request.timeline || [])].reverse().find(e => e.stage && !['Rejected', 'Revoked', 'REJECTED', 'REVOKED'].includes(e.stage));
      if (lastEntry) currentStage = lastEntry.stage;
    }

    const stageMap: Record<string, number> = {
      'ASM Review': 1,
      'ZM/RBM Review': 2,
      'ZM+RBM Review': 2,
      'ZBH Review': 3,
      'DD Lead Review': 4,
      'DD Head Review': 5,
      'NBH Approval': 6,
      'Legal Review': 7,
      'Completed': 8
    };


    if (stageMap[currentStage]) return stageMap[currentStage];

    // Case-insensitive fallback search
    const normalized = currentStage.trim().toLowerCase();
    for (const [key, val] of Object.entries(stageMap)) {
      if (key.toLowerCase() === normalized || key.toLowerCase().includes(normalized) || normalized.includes(key.toLowerCase())) {
        return val;
      }
    }

    return 1;
  };

  const currentStageIndex = getCurrentStageIndex();
  /** When the request has reached terminal success, every workflow row (including the "Completed" step) should show as done — not "In Progress". */
  const flowComplete =
    request.currentStage === 'Completed' ||
    (String(request.status || '') === 'Completed' && !['Rejected', 'Revoked'].includes(String(request.currentStage || '')));

  /** SRS §12.2 — closed failure states: do not show misleading step progress. */
  const workflowTerminalNegative =
    ['Rejected', 'Revoked'].includes(String(request.status || '')) ||
    ['Rejected', 'Revoked'].includes(String(request.currentStage || ''));

  const getLatestStageTimelineEntry = (stageName: string) => {
    const aliases: Record<string, string[]> = {
      'Submitted': ['Submitted', 'Draft'],
      'ASM Review': ['ASM Review'],
      'ZM/RBM Review': ['ZM/RBM Review', 'ZM+RBM Review', 'ZM Review', 'RBM Review'],
      'ZBH Review': ['ZBH Review'],
      'DD Lead Review': ['DD Lead Review', 'Lead Review'],
      'DD Head Review': ['DD Head Review', 'Head Review'],
      'NBH Approval': ['NBH Approval'],
      'Legal Review': ['Legal Review'],
      'Completed': ['Completed']
    };

    const stageAliases = aliases[stageName] || [stageName];
    const entries = (request.timeline || []).filter((entry: any) => {
      const entryStage = String(entry.stage || entry.targetStage || '').trim();
      return stageAliases.includes(entryStage);
    });
    return entries.length ? entries[entries.length - 1] : null;
  };

  // Centralized Permissions Utility (Fixes security gap where buttons showed for everyone)
  const getConstitutionalPermissions = () => {
    if (!request || !currentUser) {
      return { canApprove: false, canReject: false, canSendBack: false, canRevoke: false, isFinalState: false, hasCurrentUserApprovedZmRbm: false };
    }

    const currentStage = request.currentStage;
    const status = request.status;
    const userRole = currentUser.role || currentUser.roleCode;
    const userRoleCode = String(currentUser.roleCode || currentUser.role || '').trim().toUpperCase();

    const isFinalState = ['Completed', 'Rejected', 'Revoked'].includes(String(status || '')) ||
      ['Rejected', 'Revoked', 'Completed'].includes(String(currentStage || ''));

    const stageDef = workflowStages.find(s => s.name === currentStage || s.key === currentStage);

    /**
     * DB stage `Submitted` means the dealer (or internal on behalf) has already filed the request.
     * The next gate is ASM — there is no second “dealer” action on this row. ASM Approve moves to `ASM Review`.
     */
    const atSubmittedDbStage = currentStage === 'Submitted';
    const isCurrentlyAssigned =
      currentUser.roleCode === 'SUPER_ADMIN' ||
      (atSubmittedDbStage && (userRole === 'ASM' || currentUser.roleCode === 'ASM')) ||
      (!atSubmittedDbStage &&
        !!(
          (stageDef?.role === 'ASM' && userRole === 'ASM') ||
          ((stageDef?.role === 'ZM/RBM' || stageDef?.role === 'ZM+RBM') && (userRole === 'DD-ZM' || userRole === 'RBM')) ||
          (stageDef?.role === 'ZBH' && userRole === 'ZBH') ||
          (stageDef?.role === 'DD Lead' && userRole === 'DD Lead') ||
          (stageDef?.role === 'DD Head' && userRole === 'DD Head') ||
          (stageDef?.role === 'NBH' && userRole === 'NBH') ||
          (stageDef?.role === 'Legal Team' && userRole === 'Legal Admin')
        ));

    /** SRS §12.2.5 — Send Back / Revoke for ZBH, DD Lead, DD Head, NBH (not at Legal-only step). */
    const sendBackRevokeRoles = ['ZBH', 'DD Lead', 'DD Head', 'NBH'];
    const canSendBackOrRevoke =
      isCurrentlyAssigned &&
      !isFinalState &&
      (currentUser.roleCode === 'SUPER_ADMIN' || sendBackRevokeRoles.includes(userRole)) &&
      currentStage !== 'Legal Review' &&
      currentStage !== 'Submitted';

    let meta = request.metadata || {};
    if (typeof meta === 'string') {
      try {
        meta = JSON.parse(meta);
      } catch (e) {
        console.error('Failed to parse metadata', e);
        meta = {};
      }
    }
    const jointZmRbmMeta = (meta as any)?.jointApprovals?.zmRbm || {};
    const isZmRbmStage = currentStage === 'ZM/RBM Review' || currentStage === 'ZM+RBM Review';
    const actorKey = (userRoleCode === 'RBM') ? 'RBM' :
      (userRoleCode === 'DD-ZM' || userRoleCode === 'DD ZM' || userRoleCode === 'ZM') ? 'DD-ZM' : null;

    // GAP CLOSURE: Rely primarily on metadata for joint approval status. 
    const hasCurrentUserApprovedZmRbm = isZmRbmStage && actorKey && Boolean(jointZmRbmMeta?.[actorKey]?.approvedByUserId);



    return {
      canApprove: isCurrentlyAssigned && !isFinalState && !hasCurrentUserApprovedZmRbm,
      canReject: isCurrentlyAssigned && !isFinalState && !hasCurrentUserApprovedZmRbm,
      canSendBack: canSendBackOrRevoke,
      canRevoke: canSendBackOrRevoke,
      isFinalState,
      hasCurrentUserApprovedZmRbm
    };
  };

  const permissions = getConstitutionalPermissions();

  const dealerProfile = request.dealer?.dealerProfile;
  const onboardingApplication = dealerProfile?.application;
  const approvedLoiRequest = (onboardingApplication?.loiRequests || []).find((r: any) =>
    /approved/i.test(String(r?.status || ''))
  );
  const approvedLoaRequest = (onboardingApplication?.loaRequests || []).find((r: any) =>
    /approved/i.test(String(r?.status || ''))
  );
  /** `dealers.loi_date` / `dealers.loa_date` (API), else approved LOI/LOA workflow timestamps */
  const establishmentLoiDate = dealerProfile?.loiDate ?? approvedLoiRequest?.approvedAt;
  const establishmentLoaDate = dealerProfile?.loaDate ?? approvedLoaRequest?.approvedAt;

  const handleAction = (type: 'approve' | 'reject' | 'sendBack' | 'revoke') => {
    setActionType(type);
    setActionDialogError(null);
    setIsActionDialogOpen(true);
  };

  const handleSubmitAction = async (e: React.FormEvent) => {
    e.preventDefault();

    const remarksTrimmed = String(comments || '').trim();
    const isHighRiskAction = actionType === 'sendBack' || actionType === 'revoke';

    if (isHighRiskAction && remarksTrimmed.length < 5) {
      toast.error('Detailed remarks (minimum 5 characters) are required for Send Back and Revoke actions.');
      return;
    }

    if (!remarksTrimmed && actionType !== 'approve') {
      toast.error('Remarks are required for this action.');
      return;
    }

    try {
      setIsActionLoading(true);
      setActionDialogError(null);
      const actionPayload =
        actionType === 'approve'
          ? OFFBOARDING_ACTIONS.APPROVE
          : actionType === 'reject'
            ? OFFBOARDING_ACTIONS.REJECT
            : actionType === 'sendBack'
              ? OFFBOARDING_ACTIONS.SEND_BACK
              : OFFBOARDING_ACTIONS.REVOKE;
      const response = await API.updateConstitutionalChange(requestId, actionPayload, {
        comments
      }) as any;

      const payload = response?.data as { success?: boolean; message?: string } | undefined;
      /** apisauce returns { ok: false } on 4xx without throwing — must branch on this. */
      if (response?.ok && payload?.success) {
        const actionText =
          actionType === 'approve' ? 'approved' :
            actionType === 'reject' ? 'rejected' :
              actionType === 'sendBack' ? 'sent back' :
                'revoked';
        toast.success(`Request ${actionText} successfully`);
        setIsActionDialogOpen(false);
        setComments('');
        setActionDialogError(null);
        await fetchRequestDetails();
        return;
      }

      const message =
        payload?.message ||
        (response as any)?.data?.error ||
        'Failed to submit action';
      setActionDialogError(message);
      const docGate = /mandatory documents/i.test(message);
      toast.error(message, { duration: docGate ? 14000 : 8000 });
    } catch (error) {
      console.error('Submit action error:', error);
      const message =
        (error as any)?.response?.data?.message ||
        (error as any)?.message ||
        'Failed to submit action';
      setActionDialogError(message);
      toast.error(message, { duration: /mandatory documents/i.test(message) ? 14000 : 8000 });
    } finally {
      setIsActionLoading(false);
    }
  };

  const handleUploadDocument = async () => {
    if (!selectedDocType || !uploadFile) {
      toast.error('Please select document type and file');
      return;
    }

    try {
      setIsUploadingDoc(true);
      const existingDocs = Array.isArray(request.documents) ? [...request.documents] : [];
      const replaceSameSlot =
        selectedDocType !== OTHER_DOCUMENT_DOC_NUMBER;
      const existingIndex = replaceSameSlot
        ? existingDocs.findIndex((d: any) => Number(d?.docNumber) === selectedDocType)
        : -1;
      const payloadDoc = {
        docNumber: selectedDocType,
        name: documentNames[selectedDocType] || 'Other',
        fileName: uploadFile.name,
        status: 'Pending Verification',
        uploadedOn: new Date().toISOString(),
        uploadedBy: currentUser?.name || 'Dealer'
      };

      if (existingIndex >= 0) existingDocs[existingIndex] = { ...existingDocs[existingIndex], ...payloadDoc };
      else existingDocs.push(payloadDoc);

      const response = await API.uploadConstitutionalDocuments(requestId, existingDocs) as any;
      if (response.data?.success) {
        toast.success('Document uploaded successfully');
        setIsUploadDialogOpen(false);
        setSelectedDocType(null);
        setUploadFile(null);
        await fetchRequestDetails({ silent: true });
      } else {
        toast.error('Failed to upload document');
      }
    } catch (error) {
      console.error('Upload document error:', error);
      toast.error('Failed to upload document');
    } finally {
      setIsUploadingDoc(false);
    }
  };

  const handleVerifyDocument = async (targetDoc: any, targetIndex: number) => {
    try {
      const existingDocs = Array.isArray(request.documents) ? [...request.documents] : [];
      const updatedDocs = existingDocs.map((doc: any, index: number) => {
        const isTargetByIndex = index === targetIndex;
        const isTargetByDocNumber = targetDoc.docNumber && doc.docNumber === targetDoc.docNumber;
        if (!(isTargetByIndex || isTargetByDocNumber)) return doc;
        return { ...doc, status: 'Verified', verifiedOn: new Date().toISOString(), verifiedBy: currentUser?.name || 'System' };
      });

      const response = await API.uploadConstitutionalDocuments(requestId, updatedDocs) as any;
      if (response.data?.success) {
        toast.success('Document verified successfully');
        fetchRequestDetails();
      } else {
        toast.error('Failed to verify document');
      }
    } catch (error) {
      console.error('Verify document error:', error);
      toast.error('Failed to verify document');
    }
  };

  const submitRejectDocument = async () => {
    if (rejectDocIndex == null || !String(rejectDocReason).trim()) {
      toast.error('Please enter a rejection reason (SRS document verification).');
      return;
    }
    try {
      setIsRejectingDoc(true);
      const existingDocs = Array.isArray(request.documents) ? [...request.documents] : [];
      const updatedDocs = existingDocs.map((doc: any, index: number) => {
        if (index !== rejectDocIndex) return doc;
        return {
          ...doc,
          status: 'Rejected',
          rejectedOn: new Date().toISOString(),
          rejectedBy: (currentUser as any)?.fullName || 'System',
          rejectionReason: rejectDocReason.trim()
        };
      });
      const response = await API.uploadConstitutionalDocuments(requestId, updatedDocs) as any;
      if (response.data?.success) {
        toast.success('Document marked as rejected');
        setRejectDocDialogOpen(false);
        setRejectDocIndex(null);
        setRejectDocReason('');
        await fetchRequestDetails({ silent: true });
      } else {
        toast.error('Failed to reject document');
      }
    } catch (error) {
      console.error('Reject document error:', error);
      toast.error('Failed to reject document');
    } finally {
      setIsRejectingDoc(false);
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button
            variant="outline"
            onClick={onBack}
            className="flex items-center gap-2"
          >
            <ArrowLeft className="w-4 h-4" />
            Back
          </Button>
          <div>
            <h1 className="text-slate-900">{request.requestId} - Constitutional Change Details</h1>
            <p className="text-slate-600">
              {request.dealer?.dealerProfile?.businessName || request.outlet?.name || 'N/A'} ({request.dealer?.dealerProfile?.dealerCode?.dealerCode || request.outlet?.code || 'N/A'})
            </p>
          </div>
        </div>
        <Badge className={getStatusColor(request.status)}>
          {request.status}
        </Badge>
      </div>

      {/* Request Overview */}
      <Card>
        <CardHeader>
          <CardTitle>Request Overview</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <div>
              <p className="text-slate-600 text-sm mb-1">Dealer Details</p>
              <p className="text-slate-900">{request.dealer?.dealerProfile?.businessName || request.outlet?.name || 'N/A'}</p>
              <p className="text-slate-600 text-sm">{request.dealer?.dealerProfile?.dealerCode?.dealerCode || request.outlet?.code || 'N/A'}</p>
              <p className="text-slate-600 text-sm">{request.dealer?.dealerProfile?.registeredAddress || request.outlet?.city || request.outlet?.address || 'N/A'}</p>
            </div>
            <div>
              <p className="text-slate-600 text-sm mb-2">Constitutional Change</p>
              <div className="flex items-center gap-2">
                <Badge className={getTypeColor(request.oldValue || request.currentConstitution || request.outlet?.type || 'Proprietorship')}>
                  {request.oldValue || request.currentConstitution || request.outlet?.type || 'Proprietorship'}
                </Badge>
                <ArrowRight className="w-4 h-4 text-slate-400" />
                <Badge className={getTypeColor(request.newValue || request.changeType)}>
                  {request.newValue || request.changeType}
                </Badge>
              </div>
            </div>
            <div>
              <p className="text-slate-600 text-sm mb-1">Request Information</p>
              <p className="text-slate-900 text-sm">Submitted: {formatDateTime(request.createdAt)}</p>
              <p className="text-slate-600 text-sm">By: {request.dealer?.fullName || 'Dealer'}</p>
              <p className="text-slate-900 text-sm mt-2">Current Stage: {request.currentStage}</p>
            </div>
          </div>

          <div className="mt-6">
            <p className="text-slate-600 text-sm mb-2">Reason for Change</p>
            <p className="text-slate-900">{request.description}</p>
          </div>
        </CardContent>
      </Card>

      {/* Establishment Details */}
      <Card>
        <CardHeader>
          <CardTitle>Establishment & Dealer Codes</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
            <div>
              <p className="text-slate-600 text-sm mb-1">Sales Code</p>
              <p className="text-slate-900">{request.dealer?.dealerProfile?.dealerCode?.salesCode || 'N/A'}</p>
            </div>
            <div>
              <p className="text-slate-600 text-sm mb-1">Service Code</p>
              <p className="text-slate-900">{request.dealer?.dealerProfile?.dealerCode?.serviceCode || 'N/A'}</p>
            </div>
            <div>
              <p className="text-slate-600 text-sm mb-1">GMA Code</p>
              <p className="text-slate-900">{request.dealer?.dealerProfile?.dealerCode?.gmaCode || 'N/A'}</p>
            </div>
            <div>
              <p className="text-slate-600 text-sm mb-1">Gear Code</p>
              <p className="text-slate-900">{request.dealer?.dealerProfile?.dealerCode?.gearCode || 'N/A'}</p>
            </div>
            <div>
              <p className="text-slate-600 text-sm mb-1">Inauguration Date</p>
              <p className="text-slate-900">{request.dealer?.dealerProfile?.onboardedAt ? formatDateTime(request.dealer.dealerProfile.onboardedAt, 'date') : 'N/A'}</p>
            </div>
            <div>
              <p className="text-slate-600 text-sm mb-1">LOI Date</p>
              <p className="text-slate-900">{establishmentLoiDate ? formatDateTime(establishmentLoiDate, 'date') : 'N/A'}</p>
            </div>
            <div>
              <p className="text-slate-600 text-sm mb-1">LOA Date</p>
              <p className="text-slate-900">{establishmentLoaDate ? formatDateTime(establishmentLoaDate, 'date') : 'N/A'}</p>
            </div>
          </div>
        </CardContent>
      </Card>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Main Content */}
        <div className="lg:col-span-2 space-y-6">
          <Card>
            <Tabs value={activeMainTab} onValueChange={setActiveMainTab} className="w-full">
              <CardHeader className="pb-4">
                <div className="overflow-x-auto custom-scrollbar-x-slim -mx-6 px-6">
                  <TabsList className="w-max min-w-full justify-start">
                    <TabsTrigger value="workflow">Workflow Progress</TabsTrigger>
                    <TabsTrigger value="documents">Documents</TabsTrigger>
                    <TabsTrigger value="history">History & Audit Trail</TabsTrigger>
                  </TabsList>
                </div>
              </CardHeader>

              <CardContent>
                {/* Workflow Progress Tab */}
                <TabsContent value="workflow" className="mt-0">
                  {/* Progress Bar */}
                  <div className="mb-8">
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-slate-900">Overall Progress</span>
                      <span className="text-slate-600">{request.progressPercentage}%</span>
                    </div>
                    <div className="h-3 bg-slate-200 rounded-full overflow-hidden">
                      <div
                        className="h-full bg-amber-600 transition-all duration-500"
                        style={{ width: `${request.progressPercentage}%` }}
                      />
                    </div>
                  </div>

                  {/* Workflow Stages — SRS §12.2.8 style: Completed / In Progress / Pending */}
                  {workflowTerminalNegative && (
                    <div className="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800">
                      This request is closed as <strong>{String(request.status)}</strong>. The approval path below is for reference only.
                    </div>
                  )}
                  <div className="space-y-4">
                    {workflowTerminalNegative ? (
                      <ul className="list-disc space-y-1 pl-5 text-sm text-slate-600">
                        {workflowStages.map((stage) => (
                          <li key={stage.id}>
                            <span className="text-slate-900">{formatStageLabel(stage.name)}</span> — {formatStageRole(stage.role)}
                          </li>
                        ))}
                      </ul>
                    ) : (
                      workflowStages.map((stage, index) => {
                        /**
                         * While DB stage is still `Submitted`, the filing step is already done; the queue is at ASM.
                         * Show “Submitted” as completed and “ASM Review” as in progress (no extra dealer action).
                         */
                        // Adjusted logic for streamlined workflow (no separate 'Submitted' stage gate)
                        const isCompleted =
                          flowComplete ||
                          index < currentStageIndex - 1;
                        const isCurrent =
                          !flowComplete &&
                          index === currentStageIndex - 1;

                        const timelineEntry = getLatestStageTimelineEntry(stage.name);
                        const explicitFeedback = timelineEntry?.comments || timelineEntry?.feedback || timelineEntry?.remarks;
                        const isJointZmRbmStage = stage.name === 'ZM/RBM Review';
                        let metaObj = request.metadata || {};
                        if (typeof metaObj === 'string') {
                          try { metaObj = JSON.parse(metaObj); } catch (e) { metaObj = {}; }
                        }
                        const jointZmRbmMetaObj = (metaObj as any)?.jointApprovals?.zmRbm || {};
                        const rbmApproval = jointZmRbmMetaObj?.RBM;
                        const ddZmApproval = jointZmRbmMetaObj?.['DD-ZM'];
                        const currentRoleNormalized = String(currentUser?.roleCode || currentUser?.role || '').toUpperCase();
                        const currentRoleApproval =
                          currentRoleNormalized === 'RBM'
                            ? rbmApproval
                            : (currentRoleNormalized === 'DD-ZM' || currentRoleNormalized === 'DD ZM' || currentRoleNormalized === 'ZM')
                              ? ddZmApproval
                              : null;


                        return (
                          <div key={stage.id} className="flex items-start gap-4">
                            {/* Status Icon */}
                            <div className="flex flex-col items-center">
                              <div className={`w-10 h-10 rounded-full flex items-center justify-center ${isCompleted ? 'bg-green-100' :
                                  isCurrent ? 'bg-amber-100' :
                                    'bg-slate-100'
                                }`}>
                                {isCompleted ? (
                                  <CheckCircle2 className="w-5 h-5 text-green-600" />
                                ) : isCurrent ? (
                                  <Clock className="w-5 h-5 text-amber-600" />
                                ) : (
                                  <AlertCircle className="w-5 h-5 text-slate-400" />
                                )}
                              </div>
                              {index < workflowStages.length - 1 && (
                                <div className={`w-0.5 h-12 ${isCompleted ? 'bg-green-300' : 'bg-slate-200'
                                  }`} />
                              )}
                            </div>

                            {/* Stage Info */}
                            <div className={`flex-1 pb-8 ${isCurrent ? 'bg-amber-50 -ml-4 pl-4 pr-4 py-3 rounded-lg border border-amber-200' : ''}`}>
                              <div className="flex items-center justify-between">
                                <div>
                                  <h4 className={`${isCurrent ? 'text-amber-900' : 'text-slate-900'}`}>
                                    {formatStageLabel(stage.name)}
                                  </h4>
                                  <p className={`text-sm ${isCurrent ? 'text-amber-700' : 'text-slate-600'}`}>
                                    {`Responsible: ${formatStageRole(stage.role)}`}
                                  </p>

                                </div>
                                <Badge className={
                                  isCompleted ? 'bg-green-100 text-green-700 border-green-300' :
                                    isCurrent ? 'bg-amber-100 text-amber-700 border-amber-300' :
                                      'bg-slate-100 text-slate-500 border-slate-300'
                                }>
                                  {isCompleted ? 'Completed' : isCurrent ? 'In Progress' : 'Pending'}
                                </Badge>
                              </div>
                              {timelineEntry && (
                                <div className="mt-3 space-y-2">
                                  <div className="flex items-center gap-2 text-xs text-slate-600">
                                    <Badge variant="outline" className="text-[11px] normal-case">
                                      Last updated by: {timelineEntry.user || timelineEntry.userName || 'System'}
                                    </Badge>
                                    <span>{formatDateTime(timelineEntry.timestamp || timelineEntry.createdAt)}</span>
                                  </div>
                                  {explicitFeedback && (
                                    <div className="p-2 rounded border border-slate-200 bg-slate-50 text-sm text-slate-700">
                                      {explicitFeedback}
                                    </div>
                                  )}
                                </div>
                              )}
                              {isJointZmRbmStage && (
                                <div className="mt-3 rounded-md border border-slate-200 bg-slate-50 p-3">
                                  <p className="text-xs text-slate-600 mb-2">Joint approval status</p>
                                  <div className="flex flex-wrap gap-2">
                                    <Badge className={rbmApproval?.approvedByUserId ? 'bg-green-100 text-green-700 border-green-300' : 'bg-slate-100 text-slate-500 border-slate-300'}>
                                      RBM: {rbmApproval?.approvedByUserId ? 'Approved' : 'Pending'}
                                    </Badge>
                                    <Badge className={ddZmApproval?.approvedByUserId ? 'bg-green-100 text-green-700 border-green-300' : 'bg-slate-100 text-slate-500 border-slate-300'}>
                                      DD-ZM: {ddZmApproval?.approvedByUserId ? 'Approved' : 'Pending'}
                                    </Badge>
                                    {currentRoleApproval?.approvedByUserId && (
                                      <Badge className="bg-blue-100 text-blue-700 border-blue-300">
                                        Approved by you
                                      </Badge>
                                    )}
                                  </div>
                                  {(rbmApproval?.remarks || ddZmApproval?.remarks) && (
                                    <div className="mt-3 grid grid-cols-1 md:grid-cols-2 gap-2">
                                      <div className="rounded border border-slate-200 bg-white p-2">
                                        <p className="text-[11px] text-slate-500 mb-1">RBM Comment</p>
                                        <p className="text-sm text-slate-700">{rbmApproval?.remarks || '-'}</p>
                                      </div>
                                      <div className="rounded border border-slate-200 bg-white p-2">
                                        <p className="text-[11px] text-slate-500 mb-1">DD-ZM Comment</p>
                                        <p className="text-sm text-slate-700">{ddZmApproval?.remarks || '-'}</p>
                                      </div>
                                    </div>
                                  )}
                                </div>
                              )}
                            </div>
                          </div>
                        );
                      })
                    )}
                  </div>
                </TabsContent>

                {/* Documents Tab */}
                <TabsContent value="documents" className="mt-0">
                  <Tabs value={activeDocumentTab} onValueChange={setActiveDocumentTab} className="w-full">
                    <TabsList className="w-full justify-start mb-4">
                      <TabsTrigger value="required">Required for Process</TabsTrigger>
                      <TabsTrigger value="existing">Existing Documents</TabsTrigger>
                    </TabsList>

                    {/* Required Documents Sub-tab */}
                    <TabsContent value="required" className="mt-0">
                      <div className="space-y-4">
                        <div className="flex items-center justify-between gap-4">
                          <h4 className="text-slate-900">Document Checklist</h4>
                          <Dialog open={isUploadDialogOpen} onOpenChange={setIsUploadDialogOpen}>
                            <DialogTrigger asChild>
                              <Button size="sm" className="bg-amber-600 hover:bg-amber-700">
                                <Upload className="w-4 h-4 mr-2" />
                                Upload Document
                              </Button>
                            </DialogTrigger>
                            <DialogContent>
                              <DialogHeader>
                                <DialogTitle>Upload Document</DialogTitle>
                                <DialogDescription>
                                  Select the document type and upload the file
                                </DialogDescription>
                              </DialogHeader>
                              <div className="space-y-4">
                                <div>
                                  <Label>Document Type</Label>
                                  <select
                                    className="mt-1 flex h-10 w-full rounded-md border border-slate-200 bg-white px-3 py-2 text-sm ring-offset-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-500 focus-visible:ring-offset-2"
                                    value={selectedDocType != null ? String(selectedDocType) : ''}
                                    onChange={(e) => {
                                      const v = e.target.value;
                                      setSelectedDocType(v ? Number(v) : null);
                                    }}
                                  >
                                    <option value="">Select document type</option>
                                    {uploadDocumentTypeOptions.map((docNum) => (
                                      <option key={docNum} value={String(docNum)}>
                                        {docNum !== OTHER_DOCUMENT_DOC_NUMBER && isDocTypeUploaded(docNum) ? '✓ ' : ''}
                                        {documentNames[docNum] || `Document ${docNum}`}
                                      </option>
                                    ))}
                                  </select>
                                </div>
                                <div>
                                  <Label>Upload File</Label>
                                  <Input type="file" className="mt-1" onChange={(e) => setUploadFile(e.target.files?.[0] || null)} />
                                </div>
                              </div>
                              <DialogFooter>
                                <Button variant="outline" onClick={() => setIsUploadDialogOpen(false)}>
                                  Cancel
                                </Button>
                                <Button
                                  className="bg-amber-600 hover:bg-amber-700"
                                  onClick={handleUploadDocument}
                                  disabled={isUploadingDoc}
                                >
                                  {isUploadingDoc ? 'Uploading...' : 'Upload'}
                                </Button>
                              </DialogFooter>
                            </DialogContent>
                          </Dialog>
                        </div>
                        <div className="space-y-2">
                          {requiredDocs.map((docNum) => {
                            const uploaded = findUploadedForDocNum(docNum);
                            const isRejected = uploaded && String(uploaded.status) === 'Rejected';
                            const ok = uploaded && !isRejected;
                            return (
                              <div
                                key={docNum}
                                className={`flex items-center justify-between p-3 rounded-lg border ${isRejected ? 'bg-red-50 border-red-200' :
                                    ok ? 'bg-green-50 border-green-200' : 'bg-slate-50 border-slate-200'
                                  }`}
                              >
                                <div className="flex items-center gap-3">
                                  {isRejected ? (
                                    <AlertCircle className="w-5 h-5 text-red-600" />
                                  ) : ok ? (
                                    <CheckCircle2 className="w-5 h-5 text-green-600" />
                                  ) : (
                                    <AlertCircle className="w-5 h-5 text-slate-400" />
                                  )}
                                  <div>
                                    <p className={isRejected ? 'text-red-900' : ok ? 'text-green-900' : 'text-slate-900'}>
                                      {documentNames[docNum]}
                                    </p>
                                    {uploaded && (
                                      <p className={isRejected ? 'text-red-700 text-sm' : ok ? 'text-green-700 text-sm' : 'text-slate-600 text-sm'}>
                                        {uploaded.fileName || uploaded.name}
                                        {isRejected && uploaded.rejectionReason ? ` — ${uploaded.rejectionReason}` : ''}
                                      </p>
                                    )}
                                  </div>
                                </div>
                                {uploaded ? (
                                  <Badge className={getStatusColor(uploaded.status)}>
                                    {uploaded.status}
                                  </Badge>
                                ) : (
                                  <Badge className="bg-slate-100 text-slate-600 border-slate-300">
                                    Not Uploaded
                                  </Badge>
                                )}
                              </div>
                            );
                          })}
                        </div>
                      </div>
                    </TabsContent>

                    {/* Existing Documents Sub-tab */}
                    <TabsContent value="existing" className="mt-0">
                      {(request.documents || []).length > 0 ? (
                        <div>
                          <h4 className="text-slate-900 mb-3">All Uploaded Documents</h4>
                          <div className="border border-slate-200 rounded-lg overflow-hidden">
                            <Table>
                              <TableHeader>
                                <TableRow className="bg-slate-50">
                                  <TableHead>Document Name</TableHead>
                                  <TableHead>File Name</TableHead>
                                  <TableHead>Uploaded On</TableHead>
                                  <TableHead>Uploaded By</TableHead>
                                  <TableHead>Status</TableHead>
                                  <TableHead>Actions</TableHead>
                                </TableRow>
                              </TableHeader>
                              <TableBody>
                                {(request.documents || []).map((doc: any, index: number) => (
                                  <TableRow key={index}>
                                    <TableCell className="text-slate-900">
                                      {doc.docNumber ? documentNames[doc.docNumber] : doc.name}
                                    </TableCell>
                                    <TableCell className="text-slate-600">
                                      {doc.fileName || doc.name}
                                    </TableCell>
                                    <TableCell className="text-slate-600">
                                      {formatDateTime(doc.uploadedOn || doc.createdAt)}
                                    </TableCell>
                                    <TableCell className="text-slate-600">
                                      {typeof doc.uploadedBy === 'string' ? doc.uploadedBy : (doc.uploadedBy?.fullName || 'Dealer')}
                                    </TableCell>
                                    <TableCell>
                                      <Badge className={getStatusColor(doc.status)}>
                                        {doc.status}
                                      </Badge>
                                    </TableCell>
                                    <TableCell>
                                      <div className="flex items-center gap-2">
                                        <Button size="sm" variant="outline" className="h-8 w-8 p-0" title="View document">
                                          <Eye className="w-4 h-4" />
                                        </Button>
                                        <Button size="sm" variant="outline" className="h-8 w-8 p-0" title="Download document">
                                          <Download className="w-4 h-4" />
                                        </Button>
                                        {doc.status !== 'Verified' && doc.status !== 'Rejected' && (() => {
                                          const role = currentUser?.role || currentUser?.roleCode || '';
                                          // SRS §12.2 — only authorized review roles can verify constitutional documents
                                          const canVerifyDocs = ['DD Lead', 'DD Head', 'NBH', 'Legal Admin', 'DD Admin', 'Super Admin', 'SUPER_ADMIN', 'DD_ADMIN'].includes(role);
                                          return canVerifyDocs;
                                        })() && (
                                            <>
                                              <Button
                                                size="sm"
                                                className="bg-green-600 hover:bg-green-700"
                                                onClick={() => handleVerifyDocument(doc, index)}
                                              >
                                                Verify
                                              </Button>
                                              <Button
                                                size="sm"
                                                variant="outline"
                                                className="border-red-300 text-red-700 hover:bg-red-50"
                                                onClick={() => {
                                                  setRejectDocIndex(index);
                                                  setRejectDocReason('');
                                                  setRejectDocDialogOpen(true);
                                                }}
                                              >
                                                Reject
                                              </Button>
                                            </>
                                          )}
                                      </div>
                                    </TableCell>
                                  </TableRow>
                                ))}
                              </TableBody>
                            </Table>
                          </div>
                        </div>
                      ) : (
                        <div className="text-center py-8 text-slate-500">
                          No documents uploaded yet
                        </div>
                      )}
                    </TabsContent>
                  </Tabs>
                </TabsContent>

                {/* History Tab */}
                <TabsContent value="history" className="mt-0">
                  <div className="space-y-4">
                    {historyEntries.map((entry: any, index: number) => {
                      const pres = getConstitutionalHistoryPresentation(entry);

                      // Clean actor name — deduplicate "Legal Admin · Legal Admin" pattern
                      const rawActor = entry.actor?.name || entry.userName || 'System';
                      const actorParts = rawActor.split('·').map((p: string) => p.trim());
                      const actorName = [...new Set(actorParts)].join(', ');

                      // Clean action label — strip [Master data] and UUID/technical prefixes
                      const rawStage = String(entry.stage || entry.action || '').trim();
                      const cleanStage = rawStage
                        .replace(/\[Master data\]\s*/i, '')
                        .replace(/Constitutional change [A-Z0-9-]+ (completed|updated):/i, '$1:')
                        .replace(/dealer constitution updated from "(.*)" to "(.*)"\.?/i, '"$1" → "$2"')
                        .trim();

                      // Human-readable heading: prefer stage, fall back to cleaned description
                      const heading = cleanStage || pres.badge || 'Action';

                      // Remarks: prefer user-entered remarks, strip auto-generated system strings
                      const rawRemarks = String(entry.remarks || '').trim();
                      const rawDescription = String(entry.description || '').trim();
                      const systemPrefixes = [/^Approval\s*-\s*Stage:/i, /^Record (created|updated)/i, /^Document (uploaded|verified|rejected)/i];
                      const isSystemDesc = systemPrefixes.some(re => re.test(rawDescription));
                      const displayRemarks = rawRemarks || (!isSystemDesc ? rawDescription : '') || null;

                      return (
                        <div key={entry.id || index} className="flex items-start gap-4 pb-4 border-b border-slate-200 last:border-0">
                          <div className={`w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 ${pres.variant === 'success' ? 'bg-green-100' :
                              pres.variant === 'danger' ? 'bg-red-100' :
                                pres.variant === 'pending' ? 'bg-amber-100' :
                                  'bg-slate-100'
                            }`}>
                            {pres.variant === 'success' ? (
                              <CheckCircle2 className="w-5 h-5 text-green-600" />
                            ) : pres.variant === 'danger' ? (
                              <AlertCircle className="w-5 h-5 text-red-600" />
                            ) : pres.variant === 'pending' ? (
                              <Clock className="w-5 h-5 text-amber-600" />
                            ) : (
                              <Clock className="w-5 h-5 text-slate-500" />
                            )}
                          </div>
                          <div className="flex-1">
                            <div className="flex items-start justify-between gap-2">
                              <div>
                                <h4 className="text-slate-900 capitalize">{heading}</h4>
                                <p className="text-slate-500 text-sm">by <span className="font-medium text-slate-700">{actorName}</span></p>
                              </div>
                              <Badge className={getStatusColor(pres.badge)}>
                                {pres.badge.replace(/_/g, ' ')}
                              </Badge>
                            </div>
                            {displayRemarks && (
                              <div className="mt-2 p-3 bg-slate-50 rounded border border-slate-100 text-slate-700 text-sm">
                                {displayRemarks}
                              </div>
                            )}
                            <p className="text-slate-400 text-xs mt-2 font-medium uppercase tracking-wider">
                              {formatDateTime(entry.timestamp || entry.createdAt)}
                            </p>
                          </div>
                        </div>
                      );
                    })}
                    {historyEntries.length === 0 && (
                      <div className="text-center py-8 text-slate-500">
                        No history found
                      </div>
                    )}
                  </div>
                </TabsContent>
              </CardContent>
            </Tabs>
          </Card>
        </div>

        {/* Right Sidebar - Actions */}
        <div className="space-y-6">
          {/* Current Status Card */}
          <Card>
            <CardHeader>
              <CardTitle>Current Status</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <p className="text-slate-600 text-sm">Current Stage</p>
                <p className="text-slate-900">{request.currentStage}</p>
              </div>
            </CardContent>
          </Card>

          {/* Actions Card */}
          <Card>
            <CardHeader>
              <CardTitle>Actions</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              {permissions.canApprove && (
                <Button
                  className="w-full bg-green-600 hover:bg-green-700"
                  onClick={() => handleAction('approve')}
                  disabled={isActionLoading}
                >
                  {isActionLoading && actionType === 'approve' ? (
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  ) : (
                    <CheckCircle2 className="w-4 h-4 mr-2" />
                  )}
                  Approve Request
                </Button>
              )}

              {!permissions.canApprove && permissions.hasCurrentUserApprovedZmRbm && (
                <Button
                  variant="outline"
                  className="w-full border-green-300 text-green-700 bg-green-50 cursor-not-allowed"
                  disabled
                >
                  <CheckCircle2 className="w-4 h-4 mr-2" />
                  Approved by you
                </Button>
              )}

              {permissions.canReject && (
                <Button
                  variant="destructive"
                  className="w-full"
                  onClick={() => handleAction('reject')}
                  disabled={isActionLoading}
                >
                  {isActionLoading && actionType === 'reject' ? (
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  ) : (
                    <AlertCircle className="w-4 h-4 mr-2" />
                  )}
                  Reject proposal
                </Button>
              )}

              {permissions.canSendBack && (
                <Button
                  variant="outline"
                  className="w-full border-amber-300 text-amber-900 hover:bg-amber-50"
                  onClick={() => handleAction('sendBack')}
                  disabled={isActionLoading}
                >
                  {isActionLoading && actionType === 'sendBack' ? (
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  ) : (
                    <Undo2 className="w-4 h-4 mr-2" />
                  )}
                  Send back
                </Button>
              )}

              {permissions.canRevoke && (
                <Button
                  variant="outline"
                  className="w-full border-orange-300 text-orange-900 hover:bg-orange-50"
                  onClick={() => handleAction('revoke')}
                  disabled={isActionLoading}
                >
                  {isActionLoading && actionType === 'revoke' ? (
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  ) : (
                    <Ban className="w-4 h-4 mr-2" />
                  )}
                  Revoke request
                </Button>
              )}

              {!permissions.canApprove && !permissions.canReject && !permissions.canSendBack && !permissions.canRevoke && (
                <div className="text-center py-4 bg-slate-50 rounded-lg border border-dashed border-slate-200">
                  <p className="text-slate-500 text-xs px-4">
                    {permissions.isFinalState ? 'This request is finalized.' : 'No actions available for your role at this stage.'}
                  </p>
                </div>
              )}

              <div className="border-t border-slate-200 pt-3 mt-3">
                <Button
                  variant="outline"
                  className="w-full border-blue-700 text-blue-800 hover:bg-blue-50"
                  onClick={() => navigate(`/worknotes/constitutional/${request?.id || requestId}`, {
                    state: {
                      requestType: 'constitutional',
                      applicationName: request?.outlet?.name || 'Constitutional Change',
                      registrationNumber: request?.requestId || requestId || '',
                      participants: request?.participants || []
                    }
                  })}
                >
                  <MessageSquare className="w-4 h-4 mr-2" />
                  Worknotes ({(request?.worknotes || []).length})
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>

      {/* Action Dialog */}
      <Dialog
        open={isActionDialogOpen}
        onOpenChange={(open) => {
          setIsActionDialogOpen(open);
          if (!open) setActionDialogError(null);
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>
              {actionType === 'approve' ? 'Approve request' :
                actionType === 'reject' ? 'Reject proposal' :
                  actionType === 'sendBack' ? 'Send back to previous stage' :
                    'Revoke request'}
            </DialogTitle>
            <DialogDescription>
              {actionType === 'sendBack' || actionType === 'revoke'
                ? 'SRS §12.2.3: remarks are mandatory and will be posted to Work Notes for Send Back / Revoke.'
                : 'Comments will be recorded in the audit trail and work notes where applicable.'}
            </DialogDescription>
          </DialogHeader>

          <form onSubmit={handleSubmitAction} className="space-y-4">
            {actionDialogError && (
              <div
                role="alert"
                className="rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-900 flex gap-2"
              >
                <AlertCircle className="w-5 h-5 shrink-0 text-red-600" aria-hidden />
                <div className="min-w-0">
                  <p className="font-medium">This action was not completed</p>
                  <p className="mt-1 whitespace-pre-wrap break-words">{actionDialogError}</p>
                  {/mandatory documents/i.test(actionDialogError) && (
                    <p className="mt-2 text-red-800">
                      Use the <strong>Documents</strong> tab to upload every required file for this constitution
                      type, then approve again.
                    </p>
                  )}
                </div>
              </div>
            )}
            <div>
              <Label htmlFor="comments">
                {actionType === 'sendBack' || actionType === 'revoke' ? 'Remarks (required) *' : 'Comments *'}
              </Label>
            </div>
            <Textarea
              id="comments"
              value={comments}
              onChange={(e) => setComments(e.target.value)}
              placeholder={actionType === 'sendBack' || actionType === 'revoke' ? 'Enter mandatory remarks for Work Notes…' : 'Enter your comments…'}
              rows={4}
              required={actionType !== 'approve'}
            />

            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => setIsActionDialogOpen(false)}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                className={
                  actionType === 'approve' ? 'bg-green-600 hover:bg-green-700' :
                    actionType === 'reject' ? 'bg-red-600 hover:bg-red-700' :
                      actionType === 'sendBack' ? 'bg-amber-600 hover:bg-amber-700' :
                        'bg-orange-600 hover:bg-orange-700'
                }
                disabled={isActionLoading}
              >
                {isActionLoading ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    Processing...
                  </>
                ) : (
                  actionType === 'approve' ? 'Approve' :
                    actionType === 'reject' ? 'Reject' :
                      actionType === 'sendBack' ? 'Send back' :
                        'Revoke'
                )}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      <Dialog open={rejectDocDialogOpen} onOpenChange={setRejectDocDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Reject document</DialogTitle>
            <DialogDescription>
              Per SRS relocation-style verification states, mark this upload as Rejected and provide a reason for the dealer.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-3">
            <Label htmlFor="rejectReason">Rejection reason *</Label>
            <Textarea
              id="rejectReason"
              rows={4}
              value={rejectDocReason}
              onChange={(e) => setRejectDocReason(e.target.value)}
              placeholder="Explain what must be corrected or re-uploaded…"
            />
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setRejectDocDialogOpen(false)}>
              Cancel
            </Button>
            <Button
              type="button"
              variant="destructive"
              disabled={isRejectingDoc}
              onClick={() => void submitRejectDocument()}
            >
              {isRejectingDoc ? <Loader2 className="w-4 h-4 animate-spin" /> : 'Confirm reject'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

    </div>
  );
}
