
'use client';

/**
 * Phase 2: Role-Based Cockpit Dashboard Component
 */

import { useSession } from 'next-auth/react';
import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import {
  Activity,
  AlertTriangle,
  BarChart3,
  Clock,
  DollarSign,
  TrendingUp,
  Users,
  Zap,
  Settings,
  FileText,
  CheckCircle,
  XCircle
} from 'lucide-react';

import { BadgeRenewalDashboard } from './badge-renewal-dashboard';
import { DispatchRouterDashboard } from './dispatch-router-dashboard';
import { QuoteLatencyDashboard } from './quote-latency-dashboard';
import { PartnerOnboardingDashboard } from './partner-onboarding-dashboard';

interface DashboardMetrics {
  totalLeads?: number;
  totalQuotes?: number;
  totalContracts?: number;
  activeContractors?: number;
  pendingRenewals?: number;
  slaBreaches?: number;
  avgQuoteLatency?: number;
  estimatedRevenue?: number;
  myLeads?: number;
  myQuotes?: number;
  convertedLeads?: number;
  conversionRate?: number;
  avgResponseTime?: number;
  activeJobs?: number;
  completedJobs?: number;
  totalRevenue?: number;
  avgRating?: number;
  pendingBadges?: number;
  myContracts?: number;
  activeProjects?: number;
}

export default function CockpitDashboard() {
  const { data: session, status } = useSession() || {};
  const [metrics, setMetrics] = useState<DashboardMetrics>({});
  const [timeRange, setTimeRange] = useState('30d');
  const [region, setRegion] = useState('all');
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState('overview');

  useEffect(() => {
    fetchDashboardData();
  }, [timeRange, region]);

  const fetchDashboardData = async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams({
        timeRange,
        ...(region !== 'all' && { region })
      });

      const response = await fetch(`/api/cockpit?${params}`);
      const data = await response.json();

      if (response.ok) {
        setMetrics(data.metrics || {});
      }
    } catch (error) {
      console.error('Failed to fetch dashboard data:', error);
    } finally {
      setLoading(false);
    }
  };

  if (status === 'loading' || loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
      </div>
    );
  }

  const userRole = session?.user?.role || 'CUSTOMER';

  return (
    <div className="container mx-auto p-6 space-y-6">
      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Operational Cockpit</h1>
          <p className="text-muted-foreground mt-1">
            Real-time operational intelligence and command center
          </p>
        </div>

        <div className="flex items-center gap-3">
          <Select value={timeRange} onValueChange={setTimeRange}>
            <SelectTrigger className="w-32">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="7d">Last 7 days</SelectItem>
              <SelectItem value="30d">Last 30 days</SelectItem>
              <SelectItem value="90d">Last 90 days</SelectItem>
            </SelectContent>
          </Select>

          {(userRole === 'ADMIN' || userRole === 'SALES') && (
            <Select value={region} onValueChange={setRegion}>
              <SelectTrigger className="w-40">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Regions</SelectItem>
                <SelectItem value="SOUTH_AFRICA">South Africa</SelectItem>
                <SelectItem value="UNITED_KINGDOM">UK</SelectItem>
                <SelectItem value="AUSTRALIA">Australia</SelectItem>
                <SelectItem value="USA">USA</SelectItem>
              </SelectContent>
            </Select>
          )}

          <Button variant="outline" size="icon">
            <Settings className="h-4 w-4" />
          </Button>
        </div>
      </div>

      {/* Main Content Tabs */}
      <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
        <TabsList className="grid w-full grid-cols-5 lg:w-auto">
          <TabsTrigger value="overview">Overview</TabsTrigger>
          <TabsTrigger value="badges">Badge Renewals</TabsTrigger>
          <TabsTrigger value="dispatch">Dispatch Router</TabsTrigger>
          <TabsTrigger value="latency">Quote Latency</TabsTrigger>
          <TabsTrigger value="onboarding">Onboarding</TabsTrigger>
        </TabsList>

        {/* Overview Tab */}
        <TabsContent value="overview" className="space-y-6">
          {renderMetricsGrid(userRole, metrics)}
          {renderQuickActions(userRole)}
        </TabsContent>

        {/* Badge Renewals Tab */}
        <TabsContent value="badges">
          <BadgeRenewalDashboard dateRange={undefined} region={region} />
        </TabsContent>

        {/* Dispatch Router Tab */}
        <TabsContent value="dispatch">
          <DispatchRouterDashboard dateRange={undefined} region={region} />
        </TabsContent>

        {/* Quote Latency Tab */}
        <TabsContent value="latency">
          <QuoteLatencyDashboard dateRange={undefined} region={region} />
        </TabsContent>

        {/* Onboarding Tab */}
        <TabsContent value="onboarding">
          <PartnerOnboardingDashboard dateRange={undefined} region={region} />
        </TabsContent>
      </Tabs>
    </div>
  );
}

function renderMetricsGrid(role: string, metrics: DashboardMetrics) {
  switch (role) {
    case 'ADMIN':
      return (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <MetricCard
            title="Total Leads"
            value={metrics.totalLeads || 0}
            icon={<Users className="h-5 w-5" />}
            trend="+12%"
            trendUp={true}
          />
          <MetricCard
            title="Active Quotes"
            value={metrics.totalQuotes || 0}
            icon={<FileText className="h-5 w-5" />}
            trend="+8%"
            trendUp={true}
          />
          <MetricCard
            title="Pending Renewals"
            value={metrics.pendingRenewals || 0}
            icon={<AlertTriangle className="h-5 w-5 text-orange-500" />}
            urgent={!!(metrics.pendingRenewals && metrics.pendingRenewals > 5)}
          />
          <MetricCard
            title="SLA Breaches"
            value={metrics.slaBreaches || 0}
            icon={<XCircle className="h-5 w-5 text-red-500" />}
            urgent={!!(metrics.slaBreaches && metrics.slaBreaches > 0)}
          />
          <MetricCard
            title="Active Contractors"
            value={metrics.activeContractors || 0}
            icon={<Users className="h-5 w-5" />}
          />
          <MetricCard
            title="Avg Quote Latency"
            value={`${Math.round(metrics.avgQuoteLatency || 0)} min`}
            icon={<Clock className="h-5 w-5" />}
            trend="-15%"
            trendUp={false}
          />
          <MetricCard
            title="Total Contracts"
            value={metrics.totalContracts || 0}
            icon={<CheckCircle className="h-5 w-5 text-green-500" />}
          />
          <MetricCard
            title="Est. Revenue"
            value={`$${Math.round(metrics.estimatedRevenue || 0).toLocaleString()}`}
            icon={<DollarSign className="h-5 w-5" />}
            trend="+24%"
            trendUp={true}
          />
        </div>
      );

    case 'SALES':
      return (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <MetricCard
            title="My Leads"
            value={metrics.myLeads || 0}
            icon={<Users className="h-5 w-5" />}
          />
          <MetricCard
            title="My Quotes"
            value={metrics.myQuotes || 0}
            icon={<FileText className="h-5 w-5" />}
          />
          <MetricCard
            title="Converted"
            value={metrics.convertedLeads || 0}
            icon={<CheckCircle className="h-5 w-5 text-green-500" />}
          />
          <MetricCard
            title="Conversion Rate"
            value={`${Math.round(metrics.conversionRate || 0)}%`}
            icon={<TrendingUp className="h-5 w-5" />}
            trend="+5%"
            trendUp={true}
          />
          <MetricCard
            title="Avg Response Time"
            value={`${Math.round(metrics.avgResponseTime || 0)} min`}
            icon={<Clock className="h-5 w-5" />}
          />
        </div>
      );

    case 'CONTRACTOR':
      return (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <MetricCard
            title="Active Jobs"
            value={metrics.activeJobs || 0}
            icon={<Activity className="h-5 w-5" />}
          />
          <MetricCard
            title="Completed Jobs"
            value={metrics.completedJobs || 0}
            icon={<CheckCircle className="h-5 w-5 text-green-500" />}
          />
          <MetricCard
            title="Total Revenue"
            value={`$${Math.round(metrics.totalRevenue || 0).toLocaleString()}`}
            icon={<DollarSign className="h-5 w-5" />}
          />
          <MetricCard
            title="Avg Rating"
            value={`${(metrics.avgRating || 0).toFixed(1)} ⭐`}
            icon={<TrendingUp className="h-5 w-5" />}
          />
          <MetricCard
            title="Pending Badges"
            value={metrics.pendingBadges || 0}
            icon={<AlertTriangle className="h-5 w-5 text-orange-500" />}
            urgent={!!(metrics.pendingBadges && metrics.pendingBadges > 0)}
          />
        </div>
      );

    case 'CUSTOMER':
      return (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <MetricCard
            title="My Quotes"
            value={metrics.myQuotes || 0}
            icon={<FileText className="h-5 w-5" />}
          />
          <MetricCard
            title="My Contracts"
            value={metrics.myContracts || 0}
            icon={<CheckCircle className="h-5 w-5 text-green-500" />}
          />
          <MetricCard
            title="Active Projects"
            value={metrics.activeProjects || 0}
            icon={<Activity className="h-5 w-5" />}
          />
        </div>
      );

    default:
      return null;
  }
}

function renderQuickActions(role: string) {
  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Zap className="h-5 w-5" />
          Quick Actions
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
          {role === 'ADMIN' && (
            <>
              <Button variant="outline" className="h-auto py-3 flex flex-col items-center">
                <Activity className="h-5 w-5 mb-1" />
                <span className="text-xs">View All Leads</span>
              </Button>
              <Button variant="outline" className="h-auto py-3 flex flex-col items-center">
                <AlertTriangle className="h-5 w-5 mb-1" />
                <span className="text-xs">Renewal Alerts</span>
              </Button>
              <Button variant="outline" className="h-auto py-3 flex flex-col items-center">
                <BarChart3 className="h-5 w-5 mb-1" />
                <span className="text-xs">Analytics</span>
              </Button>
              <Button variant="outline" className="h-auto py-3 flex flex-col items-center">
                <Users className="h-5 w-5 mb-1" />
                <span className="text-xs">Manage Contractors</span>
              </Button>
            </>
          )}
        </div>
      </CardContent>
    </Card>
  );
}

interface MetricCardProps {
  title: string;
  value: string | number;
  icon: React.ReactNode;
  trend?: string;
  trendUp?: boolean;
  urgent?: boolean;
}

function MetricCard({ title, value, icon, trend, trendUp, urgent }: MetricCardProps) {
  return (
    <Card className={urgent ? 'border-orange-500 border-2' : ''}>
      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
        <CardTitle className="text-sm font-medium">{title}</CardTitle>
        <div className={urgent ? 'text-orange-500' : 'text-muted-foreground'}>
          {icon}
        </div>
      </CardHeader>
      <CardContent>
        <div className="text-2xl font-bold">{value}</div>
        {trend && (
          <p className={`text-xs ${trendUp ? 'text-green-600' : 'text-blue-600'} flex items-center gap-1 mt-1`}>
            {trendUp ? <TrendingUp className="h-3 w-3" /> : <Clock className="h-3 w-3" />}
            {trend} from last period
          </p>
        )}
        {urgent && (
          <Badge variant="destructive" className="mt-2 text-xs">
            Requires Attention
          </Badge>
        )}
      </CardContent>
    </Card>
  );
}
