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 { Progress } from './ui/progress';
import { Avatar, AvatarFallback } from './ui/avatar';
import { Tabs, TabsContent, TabsList, TabsTrigger } from './ui/tabs';
import { CUSTOM_REQUEST_DATABASE } from '../utils/customRequestDatabase';
import { 
  ArrowLeft, 
  Clock, 
  User, 
  FileText, 
  MessageSquare, 
  Users, 
  CheckCircle, 
  XCircle,
  Download,
  Eye,
  Flame,
  Target,
  TrendingUp,
  RefreshCw,
  Activity,
  Mail,
  Phone,
  Upload,
  UserPlus,
  Edit3,
  ClipboardList
} from 'lucide-react';

interface RequestDetailProps {
  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',
        label: 'urgent priority'
      };
    case 'standard':
      return {
        color: 'bg-blue-100 text-blue-800 border-blue-200',
        label: 'standard priority'
      };
    default:
      return {
        color: 'bg-gray-100 text-gray-800 border-gray-200',
        label: 'normal priority'
      };
  }
};

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

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':
    case 'updated':
      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" />;
    case 'reminder':
      return <Clock className="w-5 h-5 text-yellow-600" />;
    default:
      return <Activity className="w-5 h-5 text-gray-600" />;
  }
};

export function RequestDetail({
  requestId,
  onBack,
  onOpenModal,
  dynamicRequests = []
}: RequestDetailProps) {
  const [activeTab, setActiveTab] = useState('overview');

  // Get request from custom request database or dynamic requests
  const request = useMemo(() => {
    // First check static database
    const staticRequest = CUSTOM_REQUEST_DATABASE[requestId];
    if (staticRequest) return staticRequest;
    
    // Then check dynamic requests
    const dynamicRequest = dynamicRequests.find((req: any) => req.id === requestId);
    if (dynamicRequest) return dynamicRequest;
    
    return null;
  }, [requestId, dynamicRequests]);

  if (!request) {
    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">Request Not Found</h2>
          <p className="text-gray-600 mb-4">The custom 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(request.priority);
  const statusConfig = getStatusConfig(request.status);
  const slaConfig = getSLAConfig(request.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 mb-6">
          {/* Top Header */}
          <div className="p-6 border-b border-gray-200">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-4">
                <Button 
                  variant="ghost" 
                  size="icon" 
                  onClick={onBack}
                  className="rounded-lg"
                >
                  <ArrowLeft className="h-5 w-5" />
                </Button>
                
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center">
                    <FileText className="w-5 h-5 text-blue-600" />
                  </div>
                  
                  <div className="flex items-center gap-2">
                    <h1 className="text-lg font-bold text-gray-900">{request.id}</h1>
                    <Badge className={`${priorityConfig.color} rounded-full px-3`} variant="outline">
                      {priorityConfig.label}
                    </Badge>
                    <Badge className={`${statusConfig.color} rounded-full px-3`} variant="outline">
                      {statusConfig.label}
                    </Badge>
                  </div>
                </div>
              </div>
              
              <Button variant="outline" size="sm" className="gap-2">
                <RefreshCw className="w-4 h-4" />
                Refresh
              </Button>
            </div>

            <div className="mt-3 ml-14">
              <h2 className="text-xl font-semibold text-gray-900">{request.title}</h2>
            </div>
          </div>

          {/* SLA Progress */}
          <div className={`${slaConfig.bg} px-6 py-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}`}>
                {request.slaRemaining}
              </span>
            </div>
            <Progress value={request.slaProgress} className="h-2 mb-2" />
            <p className="text-xs text-gray-600">
              Due: {request.slaEndDate} • {request.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
            </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">
                {/* Request Initiator */}
                <Card>
                  <CardHeader className="pb-4">
                    <CardTitle className="flex items-center gap-2 text-base">
                      <User className="w-5 h-5 text-blue-600" />
                      Request Initiator
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="flex items-start gap-4">
                      <Avatar className="h-12 w-12 ring-2 ring-white shadow-sm">
                        <AvatarFallback className="bg-gray-700 text-white font-semibold">
                          {request.initiator?.avatar || 'U'}
                        </AvatarFallback>
                      </Avatar>
                      <div className="flex-1">
                        <h3 className="font-semibold text-gray-900">{request.initiator?.name || 'N/A'}</h3>
                        <p className="text-sm text-gray-600">{request.initiator?.role || 'N/A'}</p>
                        <p className="text-sm text-gray-500">{request.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>{request.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>{request.initiator?.phone || 'N/A'}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>

                {/* Request Details */}
                <Card>
                  <CardHeader className="pb-4">
                    <CardTitle className="flex items-center gap-2 text-base">
                      <FileText className="w-5 h-5 text-blue-600" />
                      Request Details
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div>
                      <label className="text-sm font-medium text-gray-700 block mb-2">Description</label>
                      <div className="bg-gray-50 rounded-lg p-4 border border-gray-200">
                        <p className="text-sm text-gray-700 whitespace-pre-line leading-relaxed">
                          {request.description}
                        </p>
                      </div>
                    </div>

                    {/* Additional Details */}
                    {(request.category || request.subcategory) && (
                      <div className="grid grid-cols-2 gap-4 pt-4 border-t border-gray-200">
                        {request.category && (
                          <div>
                            <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Category</label>
                            <p className="text-sm text-gray-900 font-medium mt-1">{request.category}</p>
                          </div>
                        )}
                        {request.subcategory && (
                          <div>
                            <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Subcategory</label>
                            <p className="text-sm text-gray-900 font-medium mt-1">{request.subcategory}</p>
                          </div>
                        )}
                      </div>
                    )}

                    {request.amount && (
                      <div className="pt-4 border-t border-gray-200">
                        <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Amount</label>
                        <p className="text-lg font-bold text-gray-900 mt-1">{request.amount}</p>
                      </div>
                    )}

                    <div className="grid grid-cols-2 gap-4 pt-4 border-t border-gray-200">
                      <div>
                        <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Created</label>
                        <p className="text-sm text-gray-900 font-medium mt-1">{request.createdAt}</p>
                      </div>
                      <div>
                        <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Last Updated</label>
                        <p className="text-sm text-gray-900 font-medium mt-1">{request.updatedAt}</p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </div>

              {/* Right Column - Quick Actions Sidebar (1/3 width) */}
              <div className="space-y-6">
                {/* Quick Actions */}
                <Card>
                  <CardHeader className="pb-4">
                    <CardTitle className="text-base">Quick Actions</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-2">
                    <Button 
                      variant="outline" 
                      className="w-full justify-start gap-2 bg-[#1a472a] text-white hover:bg-[#152e1f] hover:text-white border-0"
                      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 hover:bg-gray-50"
                      onClick={() => onOpenModal?.('add-approver')}
                    >
                      <UserPlus className="w-4 h-4" />
                      Add Approver
                    </Button>
                    <Button 
                      variant="outline" 
                      className="w-full justify-start gap-2 border-gray-300 hover:bg-gray-50"
                      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 Request
                      </Button>
                      <Button 
                        variant="destructive"
                        className="w-full"
                        onClick={() => onOpenModal?.('reject')}
                      >
                        <XCircle className="w-4 h-4 mr-2" />
                        Reject Request
                      </Button>
                    </div>
                  </CardContent>
                </Card>

                {/* Spectators */}
                {request.spectators && request.spectators.length > 0 && (
                  <Card>
                    <CardHeader className="pb-4">
                      <CardTitle className="text-base">Spectators</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-3">
                      {request.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 */}
          <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-blue-600" />
                      Approval Workflow
                    </CardTitle>
                    <CardDescription className="mt-2">
                      Track the approval progress through each step
                    </CardDescription>
                  </div>
                  {request.totalSteps && (
                    <Badge variant="outline" className="font-medium">
                      Step {request.currentStep} of {request.totalSteps}
                    </Badge>
                  )}
                </div>
              </CardHeader>
              <CardContent>
                {request.approvalFlow && request.approvalFlow.length > 0 ? (
                  <div className="space-y-4">
                    {request.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-blue-500 bg-blue-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-blue-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.step}: ` : ''}{step.role}
                                    </h4>
                                    <Badge variant="outline" className={
                                      isActive ? 'bg-blue-100 text-blue-800 border-blue-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>
                                </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>
                                  )}
                                  {step.actualHours !== undefined && (
                                    <p className="text-xs text-gray-600 font-medium">Completed in: {step.actualHours}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>
                              )}
                            </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-blue-600" />
                    Request Documents
                  </CardTitle>
                  <Button size="sm">
                    <Upload className="w-4 h-4 mr-2" />
                    Upload Document
                  </Button>
                </div>
              </CardHeader>
              <CardContent>
                {request.documents && request.documents.length > 0 ? (
                  <div className="space-y-3">
                    {request.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-blue-100 rounded-lg">
                            <FileText className="w-5 h-5 text-blue-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 */}
          <TabsContent value="activity">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Activity className="w-5 h-5 text-orange-600" />
                  Activity Timeline
                </CardTitle>
                <CardDescription>
                  Complete audit trail of all request activities
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {request.auditTrail && request.auditTrail.length > 0 ? request.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>
    </div>
  );
}
