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 { Input } from './ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import { Avatar, AvatarFallback, AvatarImage } from './ui/avatar';
import { Progress } from './ui/progress';
import { 
  Calendar, 
  Clock, 
  Filter, 
  Search, 
  User, 
  FileText, 
  AlertCircle, 
  CheckCircle,
  ArrowRight,
  SortAsc,
  SortDesc,
  MoreHorizontal,
  Flame,
  Target,
  Eye,
  Users,
  TrendingUp,
  RefreshCw,
  Download,
  Settings2,
  X
} from 'lucide-react';

interface Request {
  id: string;
  title: string;
  description: string;
  status: 'pending' | 'approved' | 'rejected' | 'in-review';
  priority: 'express' | 'standard';
  initiator: {
    name: string;
    avatar: string;
  };
  currentApprover?: {
    name: string;
    avatar: string;
  };
  slaProgress: number;
  slaRemaining: string;
  createdAt: string;
  dueDate: string;
  approvalStep: string;
  reason?: string;
  department?: string;
}

interface RequestsListProps {
  type: 'open' | 'closed';
  onViewRequest?: (requestId: string, requestTitle?: string) => void;
}

// Static data to prevent re-creation on each render
const MOCK_REQUESTS: Request[] = [
  {
    id: 'RE-REQ-CM-001',
    title: 'Dealer Marketing Activity Claim - Diwali Festival Campaign',
    description: 'Claim request for dealer-led Diwali festival marketing campaign using Claim Management template workflow.',
    status: 'pending',
    priority: 'standard',
    initiator: { name: 'Sneha Patil', avatar: 'SP' },
    currentApprover: { name: 'Sneha Patil (Initiator)', avatar: 'SP' },
    slaProgress: 35,
    slaRemaining: '4 days 12 hours',
    createdAt: '2024-10-07',
    dueDate: '2024-10-16',
    approvalStep: 'Initiator Review & Confirmation',
    department: 'Marketing - West Zone'
  } as any,
  {
    id: 'RE-REQ-001',
    title: 'Marketing Campaign Budget Approval',
    description: 'Request for Q4 marketing campaign budget allocation of $50,000 for digital advertising across social media platforms and content creation.',
    status: 'pending',
    priority: 'express',
    initiator: { name: 'Sarah Chen', avatar: 'SC' },
    currentApprover: { name: 'Mike Johnson', avatar: 'MJ' },
    slaProgress: 85,
    slaRemaining: '2 hours',
    createdAt: '2024-10-07',
    dueDate: '2024-10-09',
    approvalStep: 'Awaiting Finance Approval',
    department: 'Marketing'
  },
  {
    id: 'RE-REQ-002',
    title: 'IT Equipment Purchase',
    description: 'Purchase of 10 new laptops for the development team including software licenses and accessories for enhanced productivity.',
    status: 'in-review',
    priority: 'standard',
    initiator: { name: 'David Kumar', avatar: 'DK' },
    currentApprover: { name: 'Lisa Wong', avatar: 'LW' },
    slaProgress: 45,
    slaRemaining: '1 day',
    createdAt: '2024-10-06',
    dueDate: '2024-10-12',
    approvalStep: 'IT Department Review'
  },
  {
    id: 'RE-REQ-003',
    title: 'Vendor Contract Renewal',
    description: 'Annual renewal of cleaning services contract with updated terms and pricing structure for office maintenance.',
    status: 'pending',
    priority: 'standard',
    initiator: { name: 'John Doe', avatar: 'JD' },
    currentApprover: { name: 'Anna Smith', avatar: 'AS' },
    slaProgress: 90,
    slaRemaining: '30 minutes',
    createdAt: '2024-10-05',
    dueDate: '2024-10-08',
    approvalStep: 'Final Management Approval'
  },
  {
    id: 'RE-REQ-004',
    title: 'Office Space Expansion',
    description: 'Lease additional office space for growing team, 2000 sq ft in the same building with modern amenities.',
    status: 'in-review',
    priority: 'express',
    initiator: { name: 'Lisa Wong', avatar: 'LW' },
    currentApprover: { name: 'David Kumar', avatar: 'DK' },
    slaProgress: 30,
    slaRemaining: '3 days',
    createdAt: '2024-10-04',
    dueDate: '2024-10-15',
    approvalStep: 'Legal Review'
  },
  {
    id: 'RE-REQ-005',
    title: 'Employee Training Program',
    description: 'Approval for new employee onboarding and skill development training program with external consultants.',
    status: 'pending',
    priority: 'standard',
    initiator: { name: 'Anna Smith', avatar: 'AS' },
    currentApprover: { name: 'Sarah Chen', avatar: 'SC' },
    slaProgress: 60,
    slaRemaining: '12 hours',
    createdAt: '2024-10-03',
    dueDate: '2024-10-11',
    approvalStep: 'HR Approval'
  }
];

const CLOSED_REQUESTS: Request[] = [
  {
    ...MOCK_REQUESTS[0],
    status: 'approved',
    reason: 'Budget approved with quarterly review conditions'
  },
  {
    ...MOCK_REQUESTS[1],
    status: 'approved',
    reason: 'All equipment approved and ordered through preferred vendor'
  },
  {
    ...MOCK_REQUESTS[2],
    status: 'rejected',
    reason: 'Pricing not competitive, seek alternative vendors'
  },
  {
    ...MOCK_REQUESTS[3],
    status: 'approved',
    reason: 'Lease terms negotiated and approved by legal team'
  },
  {
    ...MOCK_REQUESTS[4],
    status: 'approved',
    reason: 'Program approved with budget adjustments'
  }
];

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

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

const getSLAUrgency = (progress: number) => {
  if (progress >= 80) return { color: 'bg-red-500', textColor: 'text-red-600', urgency: 'critical' };
  if (progress >= 60) return { color: 'bg-orange-500', textColor: 'text-orange-600', urgency: 'warning' };
  return { color: 'bg-green-500', textColor: 'text-green-600', urgency: 'normal' };
};

export function RequestsList({ type, onViewRequest }: RequestsListProps) {
  const [searchTerm, setSearchTerm] = useState('');
  const [priorityFilter, setPriorityFilter] = useState('all');
  const [statusFilter, setStatusFilter] = useState('all');

  const [sortBy, setSortBy] = useState<'created' | 'due' | 'priority' | 'sla'>('due');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
  const [showAdvancedFilters, setShowAdvancedFilters] = useState(false);

  const sourceRequests = type === 'open' ? MOCK_REQUESTS : CLOSED_REQUESTS;

  const filteredAndSortedRequests = useMemo(() => {
    let filtered = sourceRequests.filter(request => {
      const matchesSearch = 
        request.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
        request.id.toLowerCase().includes(searchTerm.toLowerCase()) ||
        request.initiator.name.toLowerCase().includes(searchTerm.toLowerCase());
      
      const matchesPriority = priorityFilter === 'all' || request.priority === priorityFilter;
      const matchesStatus = statusFilter === 'all' || request.status === statusFilter;
      
      return matchesSearch && matchesPriority && matchesStatus;
    });

    // Sort requests
    filtered.sort((a, b) => {
      let aValue: any, bValue: any;
      
      switch (sortBy) {
        case 'created':
          aValue = new Date(a.createdAt);
          bValue = new Date(b.createdAt);
          break;
        case 'due':
          aValue = new Date(a.dueDate);
          bValue = new Date(b.dueDate);
          break;
        case 'priority':
          const priorityOrder = { express: 2, standard: 1 };
          aValue = priorityOrder[a.priority as keyof typeof priorityOrder];
          bValue = priorityOrder[b.priority as keyof typeof priorityOrder];
          break;
        case 'sla':
          aValue = a.slaProgress;
          bValue = b.slaProgress;
          break;
        default:
          return 0;
      }
      
      if (sortOrder === 'asc') {
        return aValue > bValue ? 1 : -1;
      } else {
        return aValue < bValue ? 1 : -1;
      }
    });

    return filtered;
  }, [sourceRequests, searchTerm, priorityFilter, statusFilter, sortBy, sortOrder]);

  const clearFilters = () => {
    setSearchTerm('');
    setPriorityFilter('all');
    setStatusFilter('all');
  };

  const activeFiltersCount = [
    searchTerm,
    priorityFilter !== 'all' ? priorityFilter : null,
    statusFilter !== 'all' ? statusFilter : null
  ].filter(Boolean).length;

  return (
    <div className="space-y-6 p-6 max-w-7xl mx-auto">
      {/* Enhanced Header */}
      <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-6">
        <div className="space-y-2">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 bg-gradient-to-br from-slate-800 to-slate-900 rounded-xl flex items-center justify-center shadow-lg">
              <FileText className="w-6 h-6 text-white" />
            </div>
            <div>
              <h1 className="text-3xl font-bold text-gray-900">
                {type === 'open' ? 'Open Requests' : 'Closed Requests'}
              </h1>
              <p className="text-gray-600">
                {type === 'open' 
                  ? 'Manage and track active approval requests' 
                  : 'Review completed and archived requests'
                }
              </p>
            </div>
          </div>
        </div>
        
        <div className="flex items-center gap-3">
          <Badge variant="secondary" className="text-lg px-4 py-2 bg-slate-100 text-slate-800 font-semibold">
            {filteredAndSortedRequests.length} {type} requests
          </Badge>
          <Button variant="outline" size="sm" className="gap-2">
            <RefreshCw className="w-4 h-4" />
            Refresh
          </Button>

        </div>
      </div>

      {/* Enhanced Filters Section */}
      <Card className="shadow-lg border-0">
        <CardHeader className="pb-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-blue-100 rounded-lg">
                <Filter className="h-5 w-5 text-blue-600" />
              </div>
              <div>
                <CardTitle className="text-lg">Filters & Search</CardTitle>
                <CardDescription>
                  {activeFiltersCount > 0 && (
                    <span className="text-blue-600 font-medium">
                      {activeFiltersCount} filter{activeFiltersCount > 1 ? 's' : ''} active
                    </span>
                  )}
                </CardDescription>
              </div>
            </div>
            <div className="flex items-center gap-2">
              {activeFiltersCount > 0 && (
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={clearFilters}
                  className="text-red-600 hover:bg-red-50 gap-1"
                >
                  <X className="w-3 h-3" />
                  Clear
                </Button>
              )}
              <Button
                variant="ghost"
                size="sm"
                onClick={() => setShowAdvancedFilters(!showAdvancedFilters)}
                className="gap-2"
              >
                <Settings2 className="w-4 h-4" />
                {showAdvancedFilters ? 'Basic' : 'Advanced'}
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* Primary filters */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
              <Input
                placeholder="Search requests, IDs, or initiators..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10 h-11 bg-gray-50 border-gray-200 focus:bg-white transition-colors"
              />
            </div>
            
            <Select value={priorityFilter} onValueChange={setPriorityFilter}>
              <SelectTrigger className="h-11 bg-gray-50 border-gray-200 focus:bg-white">
                <SelectValue placeholder="All Priorities" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Priorities</SelectItem>
                <SelectItem value="express">🔥 Express</SelectItem>
                <SelectItem value="standard">🎯 Standard</SelectItem>
              </SelectContent>
            </Select>
            
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="h-11 bg-gray-50 border-gray-200 focus:bg-white">
                <SelectValue placeholder="All Statuses" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Statuses</SelectItem>
                {type === 'open' ? (
                  <>
                    <SelectItem value="pending">⏳ Pending</SelectItem>
                    <SelectItem value="in-review">👁️ In Review</SelectItem>
                  </>
                ) : (
                  <>
                    <SelectItem value="approved">✅ Approved</SelectItem>
                    <SelectItem value="rejected">❌ Rejected</SelectItem>
                  </>
                )}
              </SelectContent>
            </Select>

            <div className="flex gap-2">
              <Select value={sortBy} onValueChange={(value: any) => setSortBy(value)}>
                <SelectTrigger className="h-11 bg-gray-50 border-gray-200 focus:bg-white">
                  <SelectValue placeholder="Sort by" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="due">Due Date</SelectItem>
                  <SelectItem value="created">Date Created</SelectItem>
                  <SelectItem value="priority">Priority</SelectItem>
                  {type === 'open' && <SelectItem value="sla">SLA Progress</SelectItem>}
                </SelectContent>
              </Select>
              
              <Button
                variant="outline"
                size="sm"
                onClick={() => setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')}
                className="px-3 h-11"
              >
                {sortOrder === 'asc' ? <SortAsc className="w-4 h-4" /> : <SortDesc className="w-4 h-4" />}
              </Button>
            </div>
          </div>


        </CardContent>
      </Card>

      {/* Requests List */}
      <div className="space-y-4">
        {filteredAndSortedRequests.map((request) => {
          const priorityConfig = getPriorityConfig(request.priority);
          const statusConfig = getStatusConfig(request.status);
          const slaConfig = getSLAUrgency(request.slaProgress);
          
          return (
            <Card 
              key={request.id} 
              className="group hover:shadow-xl transition-all duration-300 cursor-pointer border-0 shadow-md hover:scale-[1.01]"
              onClick={() => onViewRequest?.(request.id, request.title)}
            >
              <CardContent className="p-6">
                <div className="flex items-start gap-6">
                  {/* Priority Indicator */}
                  <div className="flex flex-col items-center gap-2 pt-1">
                    <div className={`p-3 rounded-xl ${priorityConfig.color} border`}>
                      <priorityConfig.icon className={`w-5 h-5 ${priorityConfig.iconColor}`} />
                    </div>
                    <Badge 
                      variant="outline" 
                      className={`text-xs font-medium ${priorityConfig.color} capitalize`}
                    >
                      {request.priority}
                    </Badge>
                  </div>

                  {/* Main Content */}
                  <div className="flex-1 min-w-0 space-y-4">
                    {/* Header */}
                    <div className="flex items-start justify-between gap-4">
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-3 mb-2">
                          <h3 className="text-lg font-semibold text-gray-900 group-hover:text-blue-600 transition-colors">
                            {request.id}
                          </h3>
                          <Badge 
                            variant="outline" 
                            className={`${statusConfig.color} border font-medium`}
                          >
                            <statusConfig.icon className="w-3 h-3 mr-1" />
                            {request.status}
                          </Badge>
                          {request.department && (
                            <Badge variant="secondary" className="bg-gray-100 text-gray-700">
                              {request.department}
                            </Badge>
                          )}
                        </div>
                        <h4 className="text-xl font-bold text-gray-900 mb-2 line-clamp-1">
                          {request.title}
                        </h4>
                        <p className="text-gray-600 line-clamp-2 leading-relaxed">
                          {request.description}
                        </p>
                      </div>
                      
                      <div className="flex flex-col items-end gap-2">
                        <ArrowRight className="w-5 h-5 text-gray-400 group-hover:text-blue-600 transition-colors" />
                      </div>
                    </div>

                    {/* SLA Progress for Open Requests */}
                    {type === 'open' && (
                      <div className="bg-gray-50 rounded-lg p-4">
                        <div className="flex items-center justify-between mb-2">
                          <div className="flex items-center gap-2">
                            <Clock className="w-4 h-4 text-gray-500" />
                            <span className="text-sm font-medium text-gray-700">SLA Progress</span>
                          </div>
                          <div className="flex items-center gap-2">
                            <span className={`text-sm font-semibold ${slaConfig.textColor}`}>
                              {request.slaRemaining} remaining
                            </span>
                            {slaConfig.urgency === 'critical' && (
                              <Badge variant="destructive" className="animate-pulse text-xs">
                                URGENT
                              </Badge>
                            )}
                          </div>
                        </div>
                        <Progress 
                          value={request.slaProgress} 
                          className="h-3 bg-gray-200"
                        />
                      </div>
                    )}

                    {/* Status Info */}
                    <div className="flex items-center gap-4 p-4 bg-gray-50 rounded-lg">
                      <div className="flex items-center gap-2">
                        {type === 'open' ? (
                          <AlertCircle className="w-4 h-4 text-blue-500" />
                        ) : (
                          <CheckCircle className="w-4 h-4 text-green-500" />
                        )}
                        <span className="text-sm text-gray-700 font-medium">
                          {type === 'open' ? request.approvalStep : request.reason}
                        </span>
                      </div>
                    </div>

                    {/* Participants & Metadata */}
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-6">
                        <div className="flex items-center gap-2">
                          <Avatar className="h-8 w-8 ring-2 ring-white shadow-sm">
                            <AvatarFallback className="bg-slate-700 text-white text-sm font-semibold">
                              {request.initiator.avatar}
                            </AvatarFallback>
                          </Avatar>
                          <div>
                            <p className="text-sm font-medium text-gray-900">{request.initiator.name}</p>
                            <p className="text-xs text-gray-500">Initiator</p>
                          </div>
                        </div>
                        
                        {type === 'open' && request.currentApprover && (
                          <div className="flex items-center gap-2">
                            <Avatar className="h-8 w-8 ring-2 ring-yellow-200 shadow-sm">
                              <AvatarFallback className="bg-yellow-500 text-white text-sm font-semibold">
                                {request.currentApprover.avatar}
                              </AvatarFallback>
                            </Avatar>
                            <div>
                              <p className="text-sm font-medium text-gray-900">{request.currentApprover.name}</p>
                              <p className="text-xs text-gray-500">Current Approver</p>
                            </div>
                          </div>
                        )}
                      </div>
                      
                      <div className="text-right">
                        <div className="flex items-center gap-4 text-xs text-gray-500">
                          <span className="flex items-center gap-1">
                            <Calendar className="w-3 h-3" />
                            Created {request.createdAt}
                          </span>
                          <span>Due {request.dueDate}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          );
        })}
      </div>

      {/* Empty State */}
      {filteredAndSortedRequests.length === 0 && (
        <Card className="shadow-lg border-0">
          <CardContent className="flex flex-col items-center justify-center py-16">
            <div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4">
              <FileText className="h-8 w-8 text-gray-400" />
            </div>
            <h3 className="text-xl font-semibold text-gray-900 mb-2">No requests found</h3>
            <p className="text-gray-600 text-center max-w-md">
              {searchTerm || activeFiltersCount > 0
                ? 'Try adjusting your filters or search terms to see more results.'
                : `No ${type} requests available at the moment.`
              }
            </p>
            {activeFiltersCount > 0 && (
              <Button 
                variant="outline" 
                className="mt-4"
                onClick={clearFilters}
              >
                Clear all filters
              </Button>
            )}
          </CardContent>
        </Card>
      )}
    </div>
  );
}