import { useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Separator } from '@/components/ui/separator';
import { 
  Shield, 
  ChartColumn, 
  TrendingUp, 
  Users, 
  Clock, 
  Bell, 
  FileText, 
  LayoutDashboard, 
  Brain, 
  Share2,
  Activity,
  Search,
  ArrowUp,
  ArrowDown,
  CircleAlert
} from 'lucide-react';
import { useAuth } from '@/contexts/AuthContext';
import { AnalyticsConfig } from '@/components/admin/AnalyticsConfig';
import { UserManagement } from '@/components/admin/UserManagement';
import { TATConfig } from '@/components/admin/TATConfig';
import { NotificationConfig } from '@/components/admin/NotificationConfig';
import { DocumentConfig } from '@/components/admin/DocumentConfig';
import { DashboardConfig } from '@/components/admin/DashboardConfig';
import { AIConfig } from '@/components/admin/AIConfig';
import { SharingConfig } from '@/components/admin/SharingConfig';
import { Button } from '@/components/ui/button';
import { toast } from 'sonner';

interface KPICard {
  id: string;
  title: string;
  description: string;
  value: string | number;
  unit?: string;
  change?: number;
  changeType?: 'up' | 'down';
  period: string;
  visibleTo: string[];
  category: string;
  bgColor: string;
  borderColor: string;
  thresholdBreached?: boolean;
}

interface KPICategory {
  name: string;
  count: number;
  kpis: KPICard[];
}

export function Admin() {
  const { user } = useAuth();
  const [searchQuery, setSearchQuery] = useState('');
  const [activeTab, setActiveTab] = useState('sharing');

  // Sample KPI data organized by category
  const kpiCategories: KPICategory[] = [
    {
      name: 'Request Volume & Status',
      count: 4,
      kpis: [
        {
          id: 'total-requests',
          title: 'Total Requests Created',
          description: 'Count of all workflow requests created in a selected period.',
          value: 5,
          change: 12,
          changeType: 'up',
          period: 'Month',
          visibleTo: ['Initiator', 'Management', 'Admin'],
          category: 'Request Volume & Status',
          bgColor: 'bg-blue-50',
          borderColor: 'border-blue-200'
        },
        {
          id: 'open-requests',
          title: 'Open Requests',
          description: 'Number of workflows currently in progress with age.',
          value: 3,
          change: -5,
          changeType: 'down',
          period: 'Today',
          visibleTo: ['Initiator', 'Management', 'Admin'],
          category: 'Request Volume & Status',
          bgColor: 'bg-blue-50',
          borderColor: 'border-blue-200'
        },
        {
          id: 'approved-requests',
          title: 'Approved Requests',
          description: 'Requests fully approved and closed.',
          value: 1,
          change: 8,
          changeType: 'up',
          period: 'Month',
          visibleTo: ['Initiator', 'Management', 'Admin'],
          category: 'Request Volume & Status',
          bgColor: 'bg-blue-50',
          borderColor: 'border-blue-200'
        },
        {
          id: 'rejected-requests',
          title: 'Rejected Requests',
          description: 'Requests rejected at any approval stage.',
          value: 1,
          period: 'Month',
          visibleTo: ['Initiator', 'Management', 'Admin'],
          category: 'Request Volume & Status',
          bgColor: 'bg-blue-50',
          borderColor: 'border-blue-200'
        }
      ]
    },
    {
      name: 'TAT Efficiency',
      count: 3,
      kpis: [
        {
          id: 'avg-tat-compliance',
          title: 'Average TAT Compliance %',
          description: '% of workflows completed within defined TAT vs breached ones at every level.',
          value: 100,
          unit: '%',
          change: 3,
          changeType: 'up',
          period: 'Month',
          visibleTo: ['Initiator', 'Management', 'Admin'],
          category: 'TAT Efficiency',
          bgColor: 'bg-green-50',
          borderColor: 'border-green-200'
        },
        {
          id: 'avg-approval-cycle',
          title: 'Avg Approval Cycle Time (Days)',
          description: 'Average total time from creation to closure.',
          value: 5.2,
          unit: ' days',
          change: -15,
          changeType: 'down',
          period: 'Month',
          visibleTo: ['Initiator', 'Management', 'Admin'],
          category: 'TAT Efficiency',
          bgColor: 'bg-green-50',
          borderColor: 'border-green-200',
          thresholdBreached: true
        },
        {
          id: 'delayed-workflows',
          title: 'Delayed Workflows',
          description: 'Requests currently breaching their TAT.',
          value: 0,
          change: -2,
          changeType: 'down',
          period: 'Today',
          visibleTo: ['Initiator', 'Management', 'Admin'],
          category: 'TAT Efficiency',
          bgColor: 'bg-green-50',
          borderColor: 'border-green-200'
        }
      ]
    },
    {
      name: 'Approver Load',
      count: 2,
      kpis: [
        {
          id: 'pending-actions',
          title: 'Pending Actions (My Queue)',
          description: 'Requests currently awaiting user\'s approval with age.',
          value: 3,
          period: 'Today',
          visibleTo: ['Management', 'Admin'],
          category: 'Approver Load',
          bgColor: 'bg-orange-50',
          borderColor: 'border-orange-200'
        },
        {
          id: 'approvals-completed',
          title: 'Approvals Completed (Today/Week)',
          description: 'Count of actions taken within a time frame.',
          value: 0,
          change: 22,
          changeType: 'up',
          period: 'Week',
          visibleTo: ['Management', 'Admin'],
          category: 'Approver Load',
          bgColor: 'bg-orange-50',
          borderColor: 'border-orange-200'
        }
      ]
    },
    {
      name: 'Engagement & Quality',
      count: 2,
      kpis: [
        {
          id: 'comments-worknotes',
          title: 'Comments / Work Notes Added',
          description: 'Measures collaboration activity.',
          value: 8,
          change: 18,
          changeType: 'up',
          period: 'Week',
          visibleTo: ['Management', 'Admin'],
          category: 'Engagement & Quality',
          bgColor: 'bg-purple-50',
          borderColor: 'border-purple-200'
        },
        {
          id: 'attachments-uploaded',
          title: 'Attachments Uploaded',
          description: 'Number of documents added to workflows.',
          value: 16,
          change: 10,
          changeType: 'up',
          period: 'Month',
          visibleTo: ['Initiator', 'Management', 'Admin'],
          category: 'Engagement & Quality',
          bgColor: 'bg-purple-50',
          borderColor: 'border-purple-200'
        }
      ]
    },
    {
      name: 'AI & Closure Insights',
      count: 2,
      kpis: [
        {
          id: 'avg-conclusion-length',
          title: 'Avg Conclusion Remark Length',
          description: 'Indicates depth of closure remarks (optional).',
          value: 85,
          unit: ' chars',
          change: 5,
          changeType: 'up',
          period: 'Month',
          visibleTo: ['Management', 'Admin'],
          category: 'AI & Closure Insights',
          bgColor: 'bg-pink-50',
          borderColor: 'border-pink-200'
        },
        {
          id: 'ai-summary-adoption',
          title: 'AI Summary Adoption %',
          description: 'How many closures used AI-generated text vs manual edits.',
          value: 0,
          unit: '%',
          change: 25,
          changeType: 'up',
          period: 'Month',
          visibleTo: ['Management', 'Admin'],
          category: 'AI & Closure Insights',
          bgColor: 'bg-pink-50',
          borderColor: 'border-pink-200'
        }
      ]
    }
  ];

  // Filter KPIs based on search
  const filteredCategories = kpiCategories.map(category => ({
    ...category,
    kpis: category.kpis.filter(kpi => 
      kpi.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      kpi.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
      kpi.category.toLowerCase().includes(searchQuery.toLowerCase())
    )
  })).filter(category => category.kpis.length > 0);

  const totalActiveKPIs = kpiCategories.reduce((sum, cat) => sum + cat.count, 0);

  const getRoleBadgeColor = (role: string) => {
    switch (role) {
      case 'Initiator':
        return 'bg-blue-100 text-blue-800 border-blue-200';
      case 'Management':
        return 'bg-orange-100 text-orange-800 border-orange-200';
      case 'Admin':
        return 'bg-purple-100 text-purple-800 border-purple-200';
      default:
        return 'bg-gray-100 text-gray-800 border-gray-200';
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <h1 className="text-re-black flex items-center gap-2">
            <Shield className="w-8 h-8 text-re-green" />
            Admin Control Panel
          </h1>
          <p className="text-muted-foreground">
            Manage users, configure system settings, and control portal behavior
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={() => toast.info('COB&NDC – Coming soon')}
          >
            COB&NDC
          </Button>
          <Badge className="bg-re-green/10 text-re-green border-re-green/20 px-4 py-2">
            <Shield className="w-4 h-4 mr-2" />
            Administrator: {user?.displayName || 'Admin User'}
          </Badge>
        </div>
      </div>

      <Separator />

      {/* Main tabs */}
      <Tabs value={activeTab} onValueChange={setActiveTab} className="flex flex-col gap-2 space-y-4">
        <TabsList className="text-muted-foreground items-center justify-center rounded-xl p-[3px] bg-muted grid w-full grid-cols-9 h-auto">
          <TabsTrigger value="kpi" className="flex items-center gap-2">
            <ChartColumn className="w-4 h-4" />
            <span className="hidden sm:inline">KPI Config</span>
          </TabsTrigger>
          <TabsTrigger value="analytics" className="flex items-center gap-2">
            <TrendingUp className="w-4 h-4" />
            <span className="hidden sm:inline">Analytics</span>
          </TabsTrigger>
          <TabsTrigger value="users" className="flex items-center gap-2">
            <Users className="w-4 h-4" />
            <span className="hidden sm:inline">Users</span>
          </TabsTrigger>
          <TabsTrigger value="tat" className="flex items-center gap-2">
            <Clock className="w-4 h-4" />
            <span className="hidden sm:inline">TAT</span>
          </TabsTrigger>
          <TabsTrigger value="notifications" className="flex items-center gap-2">
            <Bell className="w-4 h-4" />
            <span className="hidden sm:inline">Notify</span>
          </TabsTrigger>
          <TabsTrigger value="documents" className="flex items-center gap-2">
            <FileText className="w-4 h-4" />
            <span className="hidden sm:inline">Docs</span>
          </TabsTrigger>
          <TabsTrigger value="dashboard" className="flex items-center gap-2">
            <LayoutDashboard className="w-4 h-4" />
            <span className="hidden sm:inline">Dashboard</span>
          </TabsTrigger>
          <TabsTrigger value="ai" className="flex items-center gap-2">
            <Brain className="w-4 h-4" />
            <span className="hidden sm:inline">AI</span>
          </TabsTrigger>
          <TabsTrigger value="sharing" className="flex items-center gap-2">
            <Share2 className="w-4 h-4" />
            <span className="hidden sm:inline">Sharing</span>
          </TabsTrigger>
        </TabsList>

        {/* KPI Config Tab */}
        <TabsContent value="kpi" className="flex-1 outline-none space-y-4">
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle>KPI Configuration</CardTitle>
                  <CardDescription>
                    Configure which KPIs are enabled, visible to specific roles, and set alert thresholds
                  </CardDescription>
                </div>
                <Badge className="bg-blue-50 text-blue-700">
                  {totalActiveKPIs} / {totalActiveKPIs} KPIs Active
                </Badge>
              </div>
            </CardHeader>
            <CardContent className="space-y-6">
              {/* Search */}
              <div className="flex items-center gap-2">
                <div className="relative flex-1">
                  <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                  <Input
                    placeholder="Search KPIs by name, description, or category..."
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    className="pl-10"
                  />
                </div>
              </div>

              {/* Category Counts */}
              <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
                {kpiCategories.map((category) => (
                  <div key={category.name} className="p-4 bg-muted/50 rounded-lg">
                    <p className="text-xs text-muted-foreground">{category.name}</p>
                    <p className="text-2xl font-semibold">{category.count}</p>
                  </div>
                ))}
              </div>

              {/* KPI Cards by Category */}
              {filteredCategories.map((category) => (
                <div key={category.name} className="space-y-3">
                  <div className="flex items-center gap-2">
                    <Activity className="w-5 h-5 text-re-green" />
                    <h3 className="font-semibold">{category.name}</h3>
                    <Badge variant="outline" className="ml-auto">
                      {category.kpis.length} Active
                    </Badge>
                  </div>
                  <div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
                    {category.kpis.map((kpi) => (
                      <div
                        key={kpi.id}
                        className={`p-4 border rounded-lg ${kpi.bgColor} ${kpi.borderColor} transition-all hover:shadow-md ${
                          kpi.thresholdBreached ? 'ring-2 ring-orange-500' : ''
                        }`}
                      >
                        <div className="flex items-start justify-between gap-4">
                          <div className="flex-1 space-y-3">
                            <div className="flex items-start justify-between">
                              <div className="flex-1">
                                <h4 className="font-medium text-sm mb-1">{kpi.title}</h4>
                                <p className="text-xs text-muted-foreground line-clamp-1">
                                  {kpi.description}
                                </p>
                              </div>
                              <Badge className="bg-green-100 text-green-800 text-xs">
                                Active
                              </Badge>
                            </div>
                            <div className="flex items-end gap-3 py-2">
                              <div>
                                <div className="flex items-baseline gap-1">
                                  <span className="text-4xl font-bold text-re-black">
                                    {kpi.value}
                                  </span>
                                  {kpi.unit && (
                                    <span className="text-lg text-muted-foreground">
                                      {kpi.unit}
                                    </span>
                                  )}
                                </div>
                              </div>
                              {kpi.change !== undefined && (
                                <div
                                  className={`flex items-center gap-1 text-xs px-2 py-1 rounded ${
                                    kpi.changeType === 'up'
                                      ? 'bg-green-100 text-green-700'
                                      : 'bg-red-100 text-red-700'
                                  }`}
                                >
                                  {kpi.changeType === 'up' ? (
                                    <ArrowUp className="w-3 h-3" />
                                  ) : (
                                    <ArrowDown className="w-3 h-3" />
                                  )}
                                  <span className="font-semibold">{Math.abs(kpi.change)}%</span>
                                </div>
                              )}
                            </div>
                            <div className="space-y-2 pt-2 border-t">
                              <div className="flex flex-wrap items-center gap-1.5">
                                <span className="text-xs text-muted-foreground">Visible:</span>
                                {kpi.visibleTo.map((role) => (
                                  <Badge
                                    key={role}
                                    className={`${getRoleBadgeColor(role)} text-xs px-1.5 py-0`}
                                  >
                                    {role}
                                  </Badge>
                                ))}
                              </div>
                              <div className="flex items-center justify-between text-xs">
                                <span className="text-muted-foreground">
                                  Period: {kpi.period}
                                </span>
                                {kpi.thresholdBreached && (
                                  <div className="flex items-center gap-1 text-orange-600">
                                    <CircleAlert className="w-3 h-3" />
                                    <span className="font-medium">Threshold Breached!</span>
                                  </div>
                                )}
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </CardContent>
          </Card>
        </TabsContent>

        {/* Analytics Tab */}
        <TabsContent value="analytics" className="flex-1 outline-none space-y-4">
          <AnalyticsConfig />
        </TabsContent>

        {/* Users Tab */}
        <TabsContent value="users" className="flex-1 outline-none space-y-4">
          <UserManagement />
        </TabsContent>

        {/* TAT Tab */}
        <TabsContent value="tat" className="flex-1 outline-none space-y-4">
          <TATConfig />
        </TabsContent>

        {/* Notifications Tab */}
        <TabsContent value="notifications" className="flex-1 outline-none space-y-4">
          <NotificationConfig />
        </TabsContent>

        {/* Documents Tab */}
        <TabsContent value="documents" className="flex-1 outline-none space-y-4">
          <DocumentConfig />
        </TabsContent>

        {/* Dashboard Tab */}
        <TabsContent value="dashboard" className="flex-1 outline-none space-y-4">
          <DashboardConfig />
        </TabsContent>

        {/* AI Tab */}
        <TabsContent value="ai" className="flex-1 outline-none space-y-4">
          <AIConfig />
        </TabsContent>

        {/* Sharing Tab */}
        <TabsContent value="sharing" className="flex-1 outline-none space-y-4">
          <SharingConfig />
        </TabsContent>
      </Tabs>
    </div>
  );
}

