import React, { useState, useMemo } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './ui/card';
import { Badge } from './ui/badge';
import { Button } from './ui/button';
import { toast } from 'sonner@2.0.3';
import { DealerDocumentModal } from './modals/DealerDocumentModal';
import { InitiatorVerificationModal } from './modals/InitiatorVerificationModal';
import { Progress } from './ui/progress';
import { Avatar, AvatarFallback } from './ui/avatar';
import { Tabs, TabsContent, TabsList, TabsTrigger } from './ui/tabs';
import { CLAIM_MANAGEMENT_DATABASE } from '../utils/claimManagementDatabase';
import { 
  ArrowLeft, 
  Clock, 
  FileText, 
  MessageSquare, 
  CheckCircle, 
  XCircle, 
  Download,
  Eye,
  Flame,
  Target,
  TrendingUp,
  RefreshCw,
  Activity,
  MapPin,
  Mail,
  Phone,
  Building,
  Receipt,
  Upload,
  UserPlus,
  ClipboardList,
  DollarSign,
  Calendar
} from 'lucide-react';

interface ClaimManagementDetailProps {
  requestId: string;
  onBack?: () => void;
  onOpenModal?: (modal: string) => void;
  dynamicRequests?: any[];
}

// Utility functions
const getPriorityConfig = (priority: string) => {
  switch (priority) {
    case 'express':
    case 'urgent':
      return {
        color: 'bg-red-100 text-red-800 border-red-200',
        icon: Flame
      };
    case 'standard':
      return {
        color: 'bg-blue-100 text-blue-800 border-blue-200',
        icon: Target
      };
    default:
      return {
        color: 'bg-gray-100 text-gray-800 border-gray-200',
        icon: Target
      };
  }
};

const getStatusConfig = (status: string) => {
  switch (status) {
    case 'pending':
      return {
        color: 'bg-yellow-100 text-yellow-800 border-yellow-200',
        icon: Clock
      };
    case 'in-review':
      return {
        color: 'bg-blue-100 text-blue-800 border-blue-200',
        icon: Eye
      };
    case 'approved':
      return {
        color: 'bg-green-100 text-green-800 border-green-200',
        icon: CheckCircle
      };
    case 'rejected':
      return {
        color: 'bg-red-100 text-red-800 border-red-200',
        icon: XCircle
      };
    default:
      return {
        color: 'bg-gray-100 text-gray-800 border-gray-200',
        icon: Clock
      };
  }
};

const getSLAConfig = (progress: number) => {
  if (progress >= 80) {
    return {
      bg: 'bg-red-50',
      color: 'bg-red-500',
      textColor: 'text-red-700'
    };
  } else if (progress >= 60) {
    return {
      bg: 'bg-orange-50',
      color: 'bg-orange-500',
      textColor: 'text-orange-700'
    };
  } else {
    return {
      bg: 'bg-green-50',
      color: 'bg-green-500',
      textColor: 'text-green-700'
    };
  }
};

const getStepIcon = (status: string) => {
  switch (status) {
    case 'approved':
      return <CheckCircle className="w-5 h-5 text-green-600" />;
    case 'rejected':
      return <XCircle className="w-5 h-5 text-red-600" />;
    case 'pending':
    case 'in-review':
      return <Clock className="w-5 h-5 text-blue-600" />;
    default:
      return <Clock className="w-5 h-5 text-gray-400" />;
  }
};

const getActionTypeIcon = (type: string) => {
  switch (type) {
    case 'approval':
    case 'approved':
      return <CheckCircle className="w-5 h-5 text-green-600" />;
    case 'rejection':
    case 'rejected':
      return <XCircle className="w-5 h-5 text-red-600" />;
    case 'comment':
      return <MessageSquare className="w-5 h-5 text-blue-600" />;
    case 'status_change':
      return <RefreshCw className="w-5 h-5 text-orange-600" />;
    case 'assignment':
      return <UserPlus className="w-5 h-5 text-purple-600" />;
    case 'created':
      return <FileText className="w-5 h-5 text-blue-600" />;
    default:
      return <Activity className="w-5 h-5 text-gray-600" />;
  }
};

export function ClaimManagementDetail({
  requestId,
  onBack,
  onOpenModal,
  dynamicRequests = []
}: ClaimManagementDetailProps) {
  const [activeTab, setActiveTab] = useState('overview');
  const [dealerDocModal, setDealerDocModal] = useState(false);
  const [initiatorVerificationModal, setInitiatorVerificationModal] = useState(false);

  // Get claim from database or dynamic requests
  const claim = useMemo(() => {
    // First check static database
    const staticClaim = CLAIM_MANAGEMENT_DATABASE[requestId];
    if (staticClaim) return staticClaim;
    
    // Then check dynamic requests
    const dynamicClaim = dynamicRequests.find((req: any) => req.id === requestId);
    if (dynamicClaim) return dynamicClaim;
    
    return null;
  }, [requestId, dynamicRequests]);

  if (!claim) {
    return (
      <div className="flex items-center justify-center h-screen">
        <div className="text-center">
          <h2 className="text-2xl font-bold text-gray-900 mb-2">Claim Not Found</h2>
          <p className="text-gray-600 mb-4">The claim request you're looking for doesn't exist.</p>
          <Button onClick={onBack}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            Go Back
          </Button>
        </div>
      </div>
    );
  }

  const priorityConfig = getPriorityConfig(claim.priority);
  const statusConfig = getStatusConfig(claim.status);
  const slaConfig = getSLAConfig(claim.slaProgress);

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto p-6">
        {/* Header Section */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-6">
          <div className="flex items-start justify-between mb-4">
            <div className="flex items-start gap-4">
              <Button 
                variant="ghost" 
                size="icon" 
                onClick={onBack}
                className="mt-1"
              >
                <ArrowLeft className="h-5 w-5" />
              </Button>
              
              <div className="flex items-start gap-4">
                <div className="w-12 h-12 rounded-full bg-purple-100 flex items-center justify-center">
                  <Receipt className="w-6 h-6 text-purple-600" />
                </div>
                
                <div>
                  <div className="flex items-center gap-3 mb-2">
                    <h1 className="text-xl font-bold text-gray-900">{claim.id}</h1>
                    <Badge className={`${priorityConfig.color}`} variant="outline">
                      {claim.priority} priority
                    </Badge>
                    <Badge className={`${statusConfig.color}`} variant="outline">
                      <statusConfig.icon className="w-3 h-3 mr-1" />
                      {claim.status}
                    </Badge>
                    <Badge className="bg-purple-100 text-purple-800 border-purple-200" variant="outline">
                      <Receipt className="w-3 h-3 mr-1" />
                      Claim Management
                    </Badge>
                  </div>
                  <h2 className="text-lg font-semibold text-gray-900">{claim.title}</h2>
                </div>
              </div>
            </div>
            
            <div className="flex items-center gap-4">
              {claim.amount && claim.amount !== 'TBD' && (
                <div className="text-right">
                  <p className="text-sm text-gray-500">Claim Amount</p>
                  <p className="text-xl font-bold text-gray-900">{claim.amount}</p>
                </div>
              )}
              <Button variant="outline" size="sm">
                <RefreshCw className="w-4 h-4 mr-2" />
                Refresh
              </Button>
            </div>
          </div>

          {/* SLA Progress */}
          <div className={`${slaConfig.bg} rounded-lg border p-4 mt-4`}>
            <div className="flex items-center justify-between mb-2">
              <div className="flex items-center gap-2">
                <Clock className={`h-4 w-4 ${slaConfig.textColor}`} />
                <span className="text-sm font-medium text-gray-900">SLA Progress</span>
              </div>
              <span className={`text-sm font-semibold ${slaConfig.textColor}`}>
                {claim.slaRemaining}
              </span>
            </div>
            <Progress value={claim.slaProgress} className="h-2 mb-2" />
            <p className="text-xs text-gray-600">
              Due: {claim.slaEndDate} • {claim.slaProgress}% elapsed
            </p>
          </div>
        </div>

        {/* Tabs */}
        <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
          <TabsList className="bg-white border border-gray-200 shadow-sm mb-6">
            <TabsTrigger value="overview" className="gap-2">
              <ClipboardList className="w-4 h-4" />
              Overview
            </TabsTrigger>
            <TabsTrigger value="workflow" className="gap-2">
              <TrendingUp className="w-4 h-4" />
              Workflow (8-Steps)
            </TabsTrigger>
            <TabsTrigger value="documents" className="gap-2">
              <FileText className="w-4 h-4" />
              Documents
            </TabsTrigger>
            <TabsTrigger value="activity" className="gap-2">
              <Activity className="w-4 h-4" />
              Activity
            </TabsTrigger>
          </TabsList>

          {/* Overview Tab */}
          <TabsContent value="overview">
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
              {/* Left Column - Main Content (2/3 width) */}
              <div className="lg:col-span-2 space-y-6">
                {/* Activity Information */}
                <Card>
                  <CardHeader className="pb-3">
                    <CardTitle className="flex items-center gap-2 text-base">
                      <Calendar className="w-5 h-5 text-blue-600" />
                      Activity Information
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Activity Name</label>
                        <p className="text-sm text-gray-900 font-medium mt-1">{claim.claimDetails?.activityName || 'N/A'}</p>
                      </div>
                      <div>
                        <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Activity Type</label>
                        <p className="text-sm text-gray-900 font-medium mt-1">{claim.claimDetails?.activityType || 'N/A'}</p>
                      </div>
                      <div>
                        <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Location</label>
                        <p className="text-sm text-gray-900 font-medium mt-1 flex items-center gap-2">
                          <MapPin className="w-4 h-4 text-gray-400" />
                          {claim.claimDetails?.location || 'N/A'}
                        </p>
                      </div>
                      <div>
                        <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Activity Date</label>
                        <p className="text-sm text-gray-900 font-medium mt-1">{claim.claimDetails?.activityDate || 'N/A'}</p>
                      </div>
                      <div>
                        <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Estimated Budget</label>
                        <p className="text-sm text-gray-900 font-medium mt-1 flex items-center gap-2">
                          <DollarSign className="w-4 h-4 text-green-600" />
                          {claim.claimDetails?.estimatedBudget || 'N/A'}
                        </p>
                      </div>
                      <div>
                        <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Period</label>
                        <p className="text-sm text-gray-900 font-medium mt-1">
                          {claim.claimDetails?.periodStart || 'N/A'} - {claim.claimDetails?.periodEnd || 'N/A'}
                        </p>
                      </div>
                    </div>

                    <div className="pt-4 border-t">
                      <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Description</label>
                      <p className="text-sm text-gray-700 mt-2 bg-gray-50 p-3 rounded-lg whitespace-pre-line">
                        {claim.claimDetails?.requestDescription || claim.description || 'N/A'}
                      </p>
                    </div>
                  </CardContent>
                </Card>

                {/* Dealer Information */}
                <Card>
                  <CardHeader className="pb-3">
                    <CardTitle className="flex items-center gap-2 text-base">
                      <Building className="w-5 h-5 text-purple-600" />
                      Dealer Information
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Dealer Code</label>
                        <p className="text-sm text-gray-900 font-medium mt-1">{claim.claimDetails?.dealerCode || 'N/A'}</p>
                      </div>
                      <div>
                        <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Dealer Name</label>
                        <p className="text-sm text-gray-900 font-medium mt-1">{claim.claimDetails?.dealerName || 'N/A'}</p>
                      </div>
                    </div>

                    <div>
                      <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Contact Information</label>
                      <div className="mt-2 space-y-2">
                        <div className="flex items-center gap-2 text-sm text-gray-700">
                          <Mail className="w-4 h-4 text-gray-400" />
                          <span>{claim.claimDetails?.dealerEmail || 'N/A'}</span>
                        </div>
                        <div className="flex items-center gap-2 text-sm text-gray-700">
                          <Phone className="w-4 h-4 text-gray-400" />
                          <span>{claim.claimDetails?.dealerPhone || 'N/A'}</span>
                        </div>
                        {claim.claimDetails?.dealerAddress && (
                          <div className="flex items-start gap-2 text-sm text-gray-700">
                            <MapPin className="w-4 h-4 text-gray-400 mt-0.5" />
                            <span>{claim.claimDetails.dealerAddress}</span>
                          </div>
                        )}
                      </div>
                    </div>
                  </CardContent>
                </Card>

                {/* Initiator Information */}
                <Card>
                  <CardHeader className="pb-3">
                    <CardTitle className="text-base">Request Initiator</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="flex items-start gap-4">
                      <Avatar className="h-14 w-14 ring-2 ring-white shadow-md">
                        <AvatarFallback className="bg-gray-700 text-white font-semibold text-lg">
                          {claim.initiator?.avatar || 'U'}
                        </AvatarFallback>
                      </Avatar>
                      <div className="flex-1">
                        <h3 className="font-semibold text-gray-900">{claim.initiator?.name || 'N/A'}</h3>
                        <p className="text-sm text-gray-600">{claim.initiator?.role || 'N/A'}</p>
                        <p className="text-sm text-gray-500">{claim.initiator?.department || 'N/A'}</p>
                        
                        <div className="mt-3 space-y-2">
                          <div className="flex items-center gap-2 text-sm text-gray-600">
                            <Mail className="w-4 h-4" />
                            <span>{claim.initiator?.email || 'N/A'}</span>
                          </div>
                          <div className="flex items-center gap-2 text-sm text-gray-600">
                            <Phone className="w-4 h-4" />
                            <span>{claim.initiator?.phone || 'N/A'}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </div>

              {/* Right Column - Quick Actions Sidebar (1/3 width) */}
              <div className="space-y-6">
                {/* Quick Actions */}
                <Card>
                  <CardHeader className="pb-3">
                    <CardTitle className="text-base">Quick Actions</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-2">
                    <Button 
                      variant="outline" 
                      className="w-full justify-start gap-2 border-gray-300"
                      onClick={() => onOpenModal?.('work-note')}
                    >
                      <MessageSquare className="w-4 h-4" />
                      Add Work Note
                    </Button>
                    <Button 
                      variant="outline" 
                      className="w-full justify-start gap-2 border-gray-300"
                      onClick={() => onOpenModal?.('add-spectator')}
                    >
                      <Eye className="w-4 h-4" />
                      Add Spectator
                    </Button>

                    <div className="pt-4 space-y-2">
                      <Button 
                        className="w-full bg-green-600 hover:bg-green-700 text-white"
                        onClick={() => onOpenModal?.('approve')}
                      >
                        <CheckCircle className="w-4 h-4 mr-2" />
                        Approve Step
                      </Button>
                      <Button 
                        variant="destructive"
                        className="w-full"
                        onClick={() => onOpenModal?.('reject')}
                      >
                        <XCircle className="w-4 h-4 mr-2" />
                        Reject Step
                      </Button>
                    </div>
                  </CardContent>
                </Card>

                {/* Spectators */}
                {claim.spectators && claim.spectators.length > 0 && (
                  <Card>
                    <CardHeader className="pb-3">
                      <CardTitle className="text-base">Spectators</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-3">
                      {claim.spectators.map((spectator: any, index: number) => (
                        <div key={index} className="flex items-center gap-3">
                          <Avatar className="h-8 w-8">
                            <AvatarFallback className="bg-blue-100 text-blue-800 text-xs font-semibold">
                              {spectator.avatar}
                            </AvatarFallback>
                          </Avatar>
                          <div className="flex-1 min-w-0">
                            <p className="text-sm font-medium text-gray-900">{spectator.name}</p>
                            <p className="text-xs text-gray-500 truncate">{spectator.role}</p>
                          </div>
                        </div>
                      ))}
                    </CardContent>
                  </Card>
                )}
              </div>
            </div>
          </TabsContent>

          {/* Workflow Tab - 8 Step Process */}
          <TabsContent value="workflow">
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <div>
                    <CardTitle className="flex items-center gap-2">
                      <TrendingUp className="w-5 h-5 text-purple-600" />
                      Claim Management Workflow
                    </CardTitle>
                    <CardDescription className="mt-2">
                      8-Step approval process for dealer claim management
                    </CardDescription>
                  </div>
                  <Badge variant="outline" className="font-medium">
                    Step {claim.currentStep} of {claim.totalSteps}
                  </Badge>
                </div>
              </CardHeader>
              <CardContent>
                {claim.approvalFlow && claim.approvalFlow.length > 0 ? (
                  <div className="space-y-4">
                    {claim.approvalFlow.map((step: any, index: number) => {
                      const isActive = step.status === 'pending' || step.status === 'in-review';
                      const isCompleted = step.status === 'approved';
                      const isRejected = step.status === 'rejected';

                      return (
                        <div
                          key={index}
                          className={`relative p-5 rounded-lg border-2 transition-all ${
                            isActive
                              ? 'border-purple-500 bg-purple-50 shadow-md'
                              : isCompleted
                              ? 'border-green-500 bg-green-50'
                              : isRejected
                              ? 'border-red-500 bg-red-50'
                              : 'border-gray-200 bg-white'
                          }`}
                        >
                          <div className="flex items-start gap-4">
                            <div className={`p-3 rounded-xl ${
                              isActive ? 'bg-purple-100' :
                              isCompleted ? 'bg-green-100' :
                              isRejected ? 'bg-red-100' :
                              'bg-gray-100'
                            }`}>
                              {getStepIcon(step.status)}
                            </div>

                            <div className="flex-1 min-w-0">
                              <div className="flex items-start justify-between gap-4 mb-2">
                                <div>
                                  <div className="flex items-center gap-2 mb-1">
                                    <h4 className="font-semibold text-gray-900">Step {step.step}: {step.role}</h4>
                                    <Badge variant="outline" className={
                                      isActive ? 'bg-purple-100 text-purple-800 border-purple-200' :
                                      isCompleted ? 'bg-green-100 text-green-800 border-green-200' :
                                      isRejected ? 'bg-red-100 text-red-800 border-red-200' :
                                      'bg-gray-100 text-gray-800 border-gray-200'
                                    }>
                                      {step.status}
                                    </Badge>
                                  </div>
                                  <p className="text-sm text-gray-600">{step.approver}</p>
                                  {step.description && (
                                    <p className="text-sm text-gray-500 mt-2 italic">{step.description}</p>
                                  )}
                                </div>
                                <div className="text-right">
                                  {step.tatHours && (
                                    <p className="text-xs text-gray-500">TAT: {step.tatHours}h</p>
                                  )}
                                  {step.elapsedHours !== undefined && step.elapsedHours > 0 && (
                                    <p className="text-xs text-gray-600 font-medium">Elapsed: {step.elapsedHours}h</p>
                                  )}
                                </div>
                              </div>

                              {step.comment && (
                                <div className="mt-3 p-3 bg-white rounded-lg border border-gray-200">
                                  <p className="text-sm text-gray-700">{step.comment}</p>
                                </div>
                              )}

                              {step.timestamp && (
                                <p className="text-xs text-gray-500 mt-2">
                                  {isCompleted ? 'Approved' : isRejected ? 'Rejected' : 'Actioned'} on {step.timestamp}
                                </p>
                              )}

                              {/* Workflow-specific Action Buttons */}
                              {isActive && (
                                <div className="mt-4 flex gap-2">
                                  {step.step === 1 && step.role === 'Dealer - Document Upload' && (
                                    <Button
                                      size="sm"
                                      onClick={() => setDealerDocModal(true)}
                                      className="bg-purple-600 hover:bg-purple-700"
                                    >
                                      <Upload className="w-4 h-4 mr-2" />
                                      Upload Documents
                                    </Button>
                                  )}
                                  {step.step === 2 && step.role === 'Initiator Evaluation' && (
                                    <Button
                                      size="sm"
                                      onClick={() => onOpenModal?.('approve')}
                                      className="bg-green-600 hover:bg-green-700"
                                    >
                                      <CheckCircle className="w-4 h-4 mr-2" />
                                      Approve & Continue
                                    </Button>
                                  )}
                                  {step.step === 4 && step.role === 'Department Lead Approval' && (
                                    <Button
                                      size="sm"
                                      onClick={() => onOpenModal?.('approve')}
                                      className="bg-green-600 hover:bg-green-700"
                                    >
                                      <CheckCircle className="w-4 h-4 mr-2" />
                                      Approve & Lock Budget
                                    </Button>
                                  )}
                                  {step.step === 5 && step.role === 'Dealer - Completion Documents' && (
                                    <Button
                                      size="sm"
                                      onClick={() => setDealerDocModal(true)}
                                      className="bg-purple-600 hover:bg-purple-700"
                                    >
                                      <Upload className="w-4 h-4 mr-2" />
                                      Upload Completion Docs
                                    </Button>
                                  )}
                                  {step.step === 6 && step.role === 'Initiator Verification' && (
                                    <Button
                                      size="sm"
                                      onClick={() => setInitiatorVerificationModal(true)}
                                      className="bg-green-600 hover:bg-green-700"
                                    >
                                      <CheckCircle className="w-4 h-4 mr-2" />
                                      Verify & Set Amount
                                    </Button>
                                  )}
                                  {step.step === 8 && step.role.includes('Credit Note') && (
                                    <Button
                                      size="sm"
                                      onClick={() => onOpenModal?.('approve')}
                                      className="bg-green-600 hover:bg-green-700"
                                    >
                                      <CheckCircle className="w-4 h-4 mr-2" />
                                      Issue Credit Note
                                    </Button>
                                  )}
                                </div>
                              )}
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                ) : (
                  <p className="text-sm text-gray-500 text-center py-8">No workflow steps defined</p>
                )}
              </CardContent>
            </Card>
          </TabsContent>

          {/* Documents Tab */}
          <TabsContent value="documents">
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <CardTitle className="flex items-center gap-2">
                    <FileText className="w-5 h-5 text-purple-600" />
                    Claim Documents
                  </CardTitle>
                  <Button size="sm">
                    <Upload className="w-4 h-4 mr-2" />
                    Upload Document
                  </Button>
                </div>
              </CardHeader>
              <CardContent>
                {claim.documents && claim.documents.length > 0 ? (
                  <div className="space-y-3">
                    {claim.documents.map((doc: any, index: number) => (
                      <div
                        key={index}
                        className="flex items-center justify-between p-4 rounded-lg border border-gray-200 hover:bg-gray-50 transition-colors"
                      >
                        <div className="flex items-center gap-3">
                          <div className="p-2 bg-purple-100 rounded-lg">
                            <FileText className="w-5 h-5 text-purple-600" />
                          </div>
                          <div>
                            <p className="font-medium text-gray-900">{doc.name}</p>
                            <p className="text-xs text-gray-500">
                              {doc.size} • Uploaded by {doc.uploadedBy} on {doc.uploadedAt}
                            </p>
                          </div>
                        </div>
                        <div className="flex items-center gap-2">
                          <Button variant="ghost" size="sm">
                            <Eye className="w-4 h-4" />
                          </Button>
                          <Button variant="ghost" size="sm">
                            <Download className="w-4 h-4" />
                          </Button>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <p className="text-sm text-gray-500 text-center py-8">No documents uploaded yet</p>
                )}
              </CardContent>
            </Card>
          </TabsContent>

          {/* Activity Tab - Audit Trail */}
          <TabsContent value="activity">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Activity className="w-5 h-5 text-orange-600" />
                  Claim Activity Timeline
                </CardTitle>
                <CardDescription>
                  Complete audit trail of all claim management activities
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {claim.auditTrail && claim.auditTrail.length > 0 ? claim.auditTrail.map((entry: any, index: number) => (
                    <div key={index} className="flex items-start gap-4 p-4 rounded-lg hover:bg-gray-50 transition-colors border border-gray-100">
                      <div className="mt-1">
                        {getActionTypeIcon(entry.type)}
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-start justify-between gap-2">
                          <div>
                            <p className="font-medium text-gray-900">{entry.action}</p>
                            <p className="text-sm text-gray-600 mt-1">{entry.details}</p>
                            <p className="text-xs text-gray-500 mt-1">by {entry.user}</p>
                          </div>
                          <span className="text-xs text-gray-500 whitespace-nowrap">{entry.timestamp}</span>
                        </div>
                      </div>
                    </div>
                  )) : (
                    <div className="text-center py-12">
                      <Activity className="w-12 h-12 text-gray-400 mx-auto mb-4" />
                      <p className="text-sm text-gray-500">No activity recorded yet</p>
                      <p className="text-xs text-gray-400 mt-2">Actions and updates will appear here</p>
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </div>

      {/* Claim Management Modals */}
      {dealerDocModal && (
        <DealerDocumentModal
          isOpen={dealerDocModal}
          onClose={() => setDealerDocModal(false)}
          onSubmit={async (documents) => {
            console.log('Dealer documents submitted:', documents);
            toast.success('Documents Uploaded', {
              description: 'Your documents have been submitted for review.',
            });
            setDealerDocModal(false);
          }}
          dealerName={claim.claimDetails?.dealerName || 'Dealer'}
          activityName={claim.claimDetails?.activityName || claim.title}
        />
      )}

      {initiatorVerificationModal && (
        <InitiatorVerificationModal
          isOpen={initiatorVerificationModal}
          onClose={() => setInitiatorVerificationModal(false)}
          onSubmit={async (data) => {
            console.log('Verification data:', data);
            toast.success('Verification Complete', {
              description: `Amount set to ${data.approvedAmount}. E-invoice will be generated.`,
            });
            setInitiatorVerificationModal(false);
          }}
          activityName={claim.claimDetails?.activityName || claim.title}
          requestedAmount={claim.claimDetails?.estimatedBudget || claim.amount || 'TBD'}
          documents={claim.documents || []}
        />
      )}
    </div>
  );
}
