import React, { useState, useMemo, useEffect } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery } from "@tanstack/react-query";
import { Link, useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";
import { Button } from "@/components/ui/button";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Users, Building2, UserPlus, TrendingUp, MapPin, Calendar, DollarSign, Award, Target, BarChart3, Shield, Leaf, Eye, Edit, Sparkles, Zap, Clock, AlertTriangle, CheckCircle, FileText, X } from "lucide-react";
import StatsCard from "@/components/staff/StatsCard";
import EcosystemWheel from "@/components/dashboard/EcosystemWheel";
import QuickMetrics from "@/components/dashboard/QuickMetrics";
import PageHeader from "@/components/common/PageHeader";
import DashboardCustomizer from "@/components/dashboard/DashboardCustomizer";
import { format, parseISO, isValid, isSameDay, startOfDay } from "date-fns";

const safeParseDate = (dateString) => {
  if (!dateString) return null;
  try {
    const date = typeof dateString === 'string' ? parseISO(dateString) : new Date(dateString);
    return isValid(date) ? date : null;
  } catch { return null; }
};

const safeFormatDate = (dateString, formatStr) => {
  const date = safeParseDate(dateString);
  if (!date) return "-";
  try { return format(date, formatStr); } catch { return "-"; }
};

const convertTo12Hour = (time24) => {
  if (!time24) return "-";
  try {
    const [hours, minutes] = time24.split(':');
    const hour = parseInt(hours);
    const ampm = hour >= 12 ? 'PM' : 'AM';
    const hour12 = hour % 12 || 12;
    return `${hour12}:${minutes} ${ampm}`;
  } catch {
    return time24;
  }
};

const getStatusBadge = (event) => {
  if (event.is_rapid) {
    return (
      <div className="inline-flex items-center gap-2 bg-red-500 text-white px-4 py-2 rounded-lg font-semibold text-xs shadow-md">
        <Zap className="w-3.5 h-3.5 fill-white" />
        RAPID
      </div>
    );
  }

  const statusConfig = {
    'Draft': { bg: 'bg-slate-500', icon: FileText },
    'Pending': { bg: 'bg-amber-500', icon: Clock },
    'Partial Staffed': { bg: 'bg-orange-500', icon: AlertTriangle },
    'Fully Staffed': { bg: 'bg-emerald-500', icon: CheckCircle },
    'Active': { bg: 'bg-blue-500', icon: Users },
    'Completed': { bg: 'bg-slate-400', icon: CheckCircle },
    'Canceled': { bg: 'bg-red-500', icon: X },
  };

  const config = statusConfig[event.status] || { bg: 'bg-slate-400', icon: Clock };
  const Icon = config.icon;

  return (
    <div className={`inline-flex items-center gap-2 ${config.bg} text-white px-4 py-2 rounded-lg font-semibold text-xs shadow-md`}>
      <Icon className="w-3.5 h-3.5" />
      {event.status}
    </div>
  );
};

const getEventTimes = (event) => {
  const firstShift = event.shifts?.[0];
  const rolesInFirstShift = firstShift?.roles || [];

  let startTime = null;
  let endTime = null;

  if (rolesInFirstShift.length > 0) {
    startTime = rolesInFirstShift[0].start_time || null;
    endTime = rolesInFirstShift[0].end_time || null;
  }
  
  return {
    startTime: startTime ? convertTo12Hour(startTime) : "-",
    endTime: endTime ? convertTo12Hour(endTime) : "-"
  };
};

const getAssignmentStatus = (event) => {
  const totalRequested = event.shifts?.reduce((accShift, shift) => {
    return accShift + (shift.roles?.reduce((accRole, role) => accRole + (role.count || 0), 0) || 0);
  }, 0) || 0;

  const assigned = event.assigned_staff?.length || 0;
  const fillPercent = totalRequested > 0 ? Math.round((assigned / totalRequested) * 100) : 0;

  if (assigned === 0) return { color: 'bg-slate-200 text-slate-600', text: '0', percent: '0%', status: 'empty' };
  if (totalRequested > 0 && assigned >= totalRequested) return { color: 'bg-emerald-500 text-white', text: assigned, percent: '100%', status: 'full' };
  if (totalRequested > 0 && assigned < totalRequested) return { color: 'bg-slate-200 text-slate-600', text: assigned, percent: `${fillPercent}%`, status: 'partial' };
  return { color: 'bg-slate-200 text-slate-600', text: assigned, percent: '0%', status: 'partial' };
};

export default function Dashboard() {
  const navigate = useNavigate();
  const [selectedLayer, setSelectedLayer] = useState(null);
  const [visibleWidgets, setVisibleWidgets] = useState([]);

  const { data: user } = useQuery({
    queryKey: ['current-user-admin-dashboard'],
    queryFn: () => base44.auth.me(),
  });

  const { data: staff, isLoading: loadingStaff } = useQuery({
    queryKey: ['staff'],
    queryFn: () => base44.entities.Staff.list('-created_date'),
    initialData: [],
  });

  const { data: events, isLoading: loadingEvents } = useQuery({
    queryKey: ['events'],
    queryFn: () => base44.entities.Event.list('-date'),
    initialData: [],
  });

  // Define available widgets for this dashboard
  const availableWidgets = useMemo(() => [
    { id: 'global_metrics', title: 'Global Metrics', description: 'Fill rate, spend, score & active events', category: 'Overview', categoryColor: 'bg-blue-100 text-blue-700' },
    { id: 'todays_orders', title: "Today's Orders", description: 'Orders scheduled for today', category: 'Operations', categoryColor: 'bg-emerald-100 text-emerald-700' },
    { id: 'ecosystem_map', title: 'Ecosystem Map', description: 'Interactive connection map', category: 'Overview', categoryColor: 'bg-purple-100 text-purple-700' },
    { id: 'quick_access', title: 'Quick Access Cards', description: 'Procurement, Operator & Vendor dashboards', category: 'Navigation', categoryColor: 'bg-amber-100 text-amber-700' },
    { id: 'workforce_overview', title: 'Workforce Overview', description: 'Recent staff and workers', category: 'Workforce', categoryColor: 'bg-pink-100 text-pink-700' },
  ], []);

  // Initialize visible widgets from user preferences or defaults
  useEffect(() => {
    const savedLayout = user?.dashboard_layout_admin;
    if (savedLayout?.widgets && savedLayout.widgets.length > 0) {
      const orderedWidgets = savedLayout.widgets
        .map(id => availableWidgets.find(w => w.id === id))
        .filter(Boolean);
      setVisibleWidgets(orderedWidgets);
    } else {
      setVisibleWidgets(availableWidgets);
    }
  }, [user, availableWidgets]);

  const isWidgetVisible = (widgetId) => visibleWidgets.some(w => w.id === widgetId);

  // Filter events for today only
  const today = startOfDay(new Date());
  const todaysEvents = events.filter(event => {
    const eventDate = safeParseDate(event.date);
    return eventDate && isSameDay(eventDate, today);
  });

  const recentStaff = staff.slice(0, 6);
  const uniqueDepartments = [...new Set(staff.map(s => s.department).filter(Boolean))];
  const uniqueLocations = [...new Set(staff.map(s => s.hub_location).filter(Boolean))];
  
  // Calculate key metrics
  const totalFillRate = 97;
  const totalSpend = 2.3;
  const overallScore = "A+";
  const activeEvents = events.filter(e => e.status === "Active" || e.status === "Confirmed").length;
  const completionRate = events.length > 0 ? Math.round((events.filter(e => e.status === "Completed").length / events.length) * 100) : 0;

  const ecosystemLayers = [
    {
      name: "Buyer(Procurements)",
      icon: DollarSign,
      color: "from-[#0A39DF] to-[#1C323E]",
      metrics: { fillRate: "97%", spend: "$2.3M", score: "A+" },
      route: "ProcurementDashboard"
    },
    {
      name: "Enterprises (Operator)",
      icon: Target,
      color: "from-emerald-500 to-emerald-700",
      metrics: { coverage: "94%", incidents: "2", satisfaction: "4.8/5" },
      route: "OperatorDashboard"
    },
    {
      name: "Sectors (Execution)",
      icon: Building2,
      color: "from-purple-500 to-purple-700",
      metrics: { active: activeEvents, revenue: "$1.8M", growth: "+12%" },
      route: "OperatorDashboard"
    },
    {
      name: "Partner",
      icon: Users,
      color: "from-pink-500 to-pink-700",
      metrics: { total: "45", retention: "92%", nps: "8.5" },
      route: "Business"
    },
    {
      name: "Approved Vendor",
      icon: Award,
      color: "from-amber-500 to-amber-700",
      metrics: { partners: "12", rating: "4.7/5", compliance: "98%" },
      route: "VendorDashboard"
    },
    {
      name: "Workforce",
      icon: UserPlus,
      color: "from-[#0A39DF] to-[#0A39DF]/80",
      metrics: { total: staff.length, active: staff.filter(s => s.check_in).length, trained: "89%" },
      route: "WorkforceDashboard"
    }
  ];

  return (
    <div className="p-4 md:p-8 bg-gradient-to-br from-slate-50 to-slate-100 min-h-screen">
      <div className="max-w-7xl mx-auto">
        <PageHeader 
          title={
            <div className="flex items-center gap-2">
              <span>Welcome to KROW</span>
              {import.meta.env.VITE_APP_ENV === 'staging' && <span className="bg-yellow-100 text-yellow-800 text-xs font-semibold px-2.5 py-0.5 rounded-full">Staging</span>}
              {import.meta.env.VITE_APP_ENV === 'dev' && <span className="bg-slate-200 text-slate-800 text-xs font-semibold px-2.5 py-0.5 rounded-full">Dev</span>}
            </div>
          }
          subtitle="Your Complete Workforce Management Ecosystem"
          actions={
            <>
              <DashboardCustomizer
                user={user}
                availableWidgets={availableWidgets}
                currentLayout={visibleWidgets}
                onLayoutChange={setVisibleWidgets}
                dashboardType="admin"
              />
              <Button variant="outline" className="border-slate-300 hover:bg-slate-100">
                <BarChart3 className="w-4 h-4 mr-2" />
                Reports
              </Button>
              <Link to={createPageUrl("Events")}>
                <Button className="bg-gradient-to-r from-[#0A39DF] to-[#1C323E] hover:from-[#0A39DF]/90 hover:to-[#1C323E]/90 text-white shadow-lg">
                  <Calendar className="w-5 h-5 mr-2" />
                  View All Orders
                </Button>
              </Link>
            </>
          }
        />

        {/* Global Metrics */}
        {isWidgetVisible('global_metrics') && (
          <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
            <StatsCard
              title="Fill Rate"
              value={`${totalFillRate}%`}
              icon={Target}
              gradient="bg-gradient-to-br from-[#0A39DF] to-[#1C323E]"
              change="+2.5% this month"
            />
            <StatsCard
              title="Total Spend"
              value={`$${totalSpend}M`}
              icon={DollarSign}
              gradient="bg-gradient-to-br from-emerald-500 to-emerald-700"
              change="+$180K this month"
            />
            <StatsCard
              title="Overall Score"
              value={overallScore}
              icon={Award}
              gradient="bg-gradient-to-br from-amber-500 to-amber-600"
            />
            <StatsCard
              title="Active Events"
              value={activeEvents}
              icon={Calendar}
              gradient="bg-gradient-to-br from-purple-500 to-purple-700"
              change={`${completionRate}% completion rate`}
            />
          </div>
        )}

        {/* Today's Orders Section */}
        {isWidgetVisible('todays_orders') && (
          <Card className="mb-8 border-slate-200 shadow-lg">
            <CardHeader className="bg-gradient-to-br from-slate-50 to-white border-b border-slate-100">
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle className="text-[#1C323E] flex items-center gap-2">
                    <Calendar className="w-6 h-6 text-[#0A39DF]" />
                    Today's Orders - {format(today, 'EEEE, MMMM d, yyyy')}
                  </CardTitle>
                  <p className="text-sm text-slate-500 mt-1">Orders scheduled for today only</p>
                </div>
                <Link to={createPageUrl("Events")}>
                  <Button variant="outline" className="border-slate-300">
                    View All Orders
                  </Button>
                </Link>
              </div>
            </CardHeader>
            <CardContent className="p-0">
              {todaysEvents.length === 0 ? (
                <div className="text-center py-12 text-slate-500">
                  <Calendar className="w-12 h-12 mx-auto mb-3 text-slate-300" />
                  <p className="font-medium">No orders scheduled for today</p>
                </div>
              ) : (
                <div className="overflow-x-auto">
                  <Table>
                    <TableHeader>
                      <TableRow className="bg-slate-50 hover:bg-slate-50 border-b">
                        <TableHead className="font-semibold text-slate-600 uppercase text-[10px] tracking-wide h-10">BUSINESS</TableHead>
                        <TableHead className="font-semibold text-slate-600 uppercase text-[10px] tracking-wide">HUB</TableHead>
                        <TableHead className="font-semibold text-slate-600 uppercase text-[10px] tracking-wide">EVENT</TableHead>
                        <TableHead className="font-semibold text-slate-600 uppercase text-[10px] tracking-wide">DATE & TIME</TableHead>
                        <TableHead className="font-semibold text-slate-600 uppercase text-[10px] tracking-wide">STATUS</TableHead>
                        <TableHead className="font-semibold text-slate-600 uppercase text-[10px] tracking-wide text-center">REQUESTED</TableHead>
                        <TableHead className="font-semibold text-slate-600 uppercase text-[10px] tracking-wide text-center">ASSIGNED</TableHead>
                        <TableHead className="font-semibold text-slate-600 uppercase text-[10px] tracking-wide text-center">ACTIONS</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {todaysEvents.map((event) => {
                        const assignmentStatus = getAssignmentStatus(event);
                        const eventTimes = getEventTimes(event);
                        const eventDate = safeParseDate(event.date);
                        const dayOfWeek = eventDate ? format(eventDate, 'EEEE') : '';
                        
                        return (
                          <TableRow key={event.id} className="hover:bg-slate-50 transition-colors border-b">
                            <TableCell className="py-3">
                              <p className="text-sm text-slate-700 font-medium">{event.business_name || "—"}</p>
                            </TableCell>
                            <TableCell className="py-3">
                              <div className="flex items-center gap-1.5 text-sm text-slate-500">
                                <MapPin className="w-3.5 h-3.5" />
                                {event.hub || event.event_location || "Main Hub"}
                              </div>
                            </TableCell>
                            <TableCell className="py-3">
                              <p className="font-semibold text-slate-900 text-sm">{event.event_name}</p>
                            </TableCell>
                            <TableCell className="py-3">
                              <div className="space-y-0.5">
                                <p className="text-sm text-slate-900 font-semibold">{eventDate ? format(eventDate, 'MM.dd.yyyy') : '-'}</p>
                                <p className="text-xs text-slate-500">{dayOfWeek}</p>
                                <div className="flex items-center gap-1 text-xs text-slate-600 mt-1">
                                  <Clock className="w-3 h-3" />
                                  <span>{eventTimes.startTime} - {eventTimes.endTime}</span>
                                </div>
                              </div>
                            </TableCell>
                            <TableCell className="py-3">
                              {getStatusBadge(event)}
                            </TableCell>
                            <TableCell className="text-center py-3">
                              <span className="font-semibold text-slate-700 text-sm">{event.requested || 0}</span>
                            </TableCell>
                            <TableCell className="text-center py-3">
                              <div className="flex flex-col items-center gap-1">
                                <div className={`w-10 h-10 rounded-full ${assignmentStatus.color} flex items-center justify-center font-bold text-sm`}>
                                  {assignmentStatus.text}
                                </div>
                                <span className="text-[10px] text-slate-500 font-medium">{assignmentStatus.percent}</span>
                              </div>
                            </TableCell>
                            <TableCell className="py-3">
                              <div className="flex items-center justify-center gap-1">
                                <Button 
                                  variant="ghost" 
                                  size="icon" 
                                  onClick={() => navigate(createPageUrl(`EventDetail?id=${event.id}`))} 
                                  className="hover:bg-slate-100 h-8 w-8"
                                  title="View"
                                >
                                  <Eye className="w-4 h-4" />
                                </Button>
                                <Button 
                                  variant="ghost" 
                                  size="icon" 
                                  onClick={() => navigate(createPageUrl(`EditEvent?id=${event.id}`))}
                                  className="hover:bg-slate-100 h-8 w-8"
                                  title="Edit"
                                >
                                  <Edit className="w-4 h-4" />
                                </Button>
                                {event.invoice_id && (
                                  <Button 
                                    variant="ghost" 
                                    size="icon" 
                                    onClick={() => navigate(createPageUrl(`Invoices?id=${event.invoice_id}`))}
                                    className="hover:bg-slate-100 h-8 w-8"
                                    title="View Invoice"
                                  >
                                    <FileText className="w-4 h-4 text-blue-600" />
                                  </Button>
                                )}
                              </div>
                            </TableCell>
                          </TableRow>
                        );
                      })}
                    </TableBody>
                  </Table>
                </div>
              )}
            </CardContent>
          </Card>
        )}

        {/* Ecosystem Puzzle */}
        {isWidgetVisible('ecosystem_map') && (
          <Card className="mb-8 border-slate-200 shadow-xl overflow-hidden">
            <CardHeader className="bg-gradient-to-br from-slate-50 to-white border-b border-slate-100">
              <CardTitle className="text-[#1C323E] flex items-center gap-2">
                <Target className="w-6 h-6 text-[#0A39DF]" />
                Ecosystem Connection Map
              </CardTitle>
              <p className="text-sm text-slate-500 mt-1">Interactive puzzle showing how each layer connects • Hover to see metrics • Click to explore</p>
            </CardHeader>
            <CardContent className="p-8">
              <EcosystemWheel 
                layers={ecosystemLayers}
                onLayerClick={(layer) => navigate(createPageUrl(layer.route))}
                selectedLayer={selectedLayer}
                onLayerHover={setSelectedLayer}
              />
            </CardContent>
          </Card>
        )}

        {/* Quick Access Cards */}
        {isWidgetVisible('quick_access') && (
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
            <QuickMetrics
              title="Procurement & Vendor Intelligence"
              description="Vendor efficiency, spend analysis, compliance tracking"
              icon={Shield}
              metrics={[
                { label: "Vendor Score", value: "A+", color: "text-green-600" },
                { label: "Compliance", value: "98%", color: "text-blue-600" },
                { label: "ESG Rating", value: "B+", color: "text-emerald-600" }
              ]}
              route="ProcurementDashboard"
              gradient="from-[#0A39DF]/10 to-[#1C323E]/10"
            />

            <QuickMetrics
              title="Operator & Sector Dashboard"
              description="Live coverage, demand forecast, incident tracking"
              icon={MapPin}
              metrics={[
                { label: "Coverage", value: "94%", color: "text-green-600" },
                { label: "Incidents", value: "2", color: "text-yellow-600" },
                { label: "Forecast Accuracy", value: "91%", color: "text-blue-600" }
              ]}
              route="OperatorDashboard"
              gradient="from-emerald-500/10 to-emerald-700/10"
            />

            <QuickMetrics
              title="Vendor Dashboard"
              description="Orders, invoices, workforce pulse, KROW score"
              icon={Award}
              metrics={[
                { label: "Fill Rate", value: "97%", color: "text-green-600" },
                { label: "Attendance", value: "95%", color: "text-blue-600" },
                { label: "Training", value: "92%", color: "text-purple-600" }
              ]}
              route="VendorDashboard"
              gradient="from-amber-500/10 to-amber-700/10"
            />
          </div>
        )}

        {/* Workforce Section */}
        {isWidgetVisible('workforce_overview') && (
          <Card className="border-slate-200 shadow-lg">
            <CardHeader className="bg-gradient-to-br from-slate-50 to-white border-b border-slate-100">
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle className="text-[#1C323E] flex items-center gap-2">
                    <Users className="w-6 h-6 text-[#0A39DF]" />
                    Workforce Overview
                  </CardTitle>
                  <p className="text-sm text-slate-500 mt-1">Recent additions and active workers</p>
                </div>
                <div className="flex gap-2">
                  <Link to={createPageUrl("WorkforceDashboard")}>
                    <Button variant="outline" className="border-slate-300">
                      View Workforce App
                    </Button>
                  </Link>
                  <Link to={createPageUrl("StaffDirectory")}>
                    <Button className="bg-[#0A39DF] hover:bg-[#0A39DF]/90">
                      View All Staff
                    </Button>
                  </Link>
                </div>
              </div>
            </CardHeader>
            <CardContent className="p-6">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                {recentStaff.slice(0, 3).map((member) => (
                  <div key={member.id} className="p-4 rounded-lg border border-slate-200 hover:border-[#0A39DF] hover:shadow-md transition-all">
                    <div className="flex items-center gap-3 mb-3">
                      <div className="w-12 h-12 bg-gradient-to-br from-[#0A39DF] to-[#1C323E] rounded-xl flex items-center justify-center text-white font-bold">
                        {member.initial || member.employee_name?.charAt(0)}
                      </div>
                      <div>
                        <h4 className="font-semibold text-[#1C323E]">{member.employee_name}</h4>
                        <p className="text-sm text-slate-500">{member.position}</p>
                      </div>
                    </div>
                    <div className="space-y-2 text-sm">
                      <div className="flex justify-between">
                        <span className="text-slate-500">Rating:</span>
                        <span className="font-semibold">{member.rating || 0}/5 ⭐</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-slate-500">Coverage:</span>
                        <span className="font-semibold text-green-600">{member.shift_coverage_percentage || 0}%</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-slate-500">Cancellations:</span>
                        <span className="font-semibold text-red-600">{member.cancellation_count || 0}</span>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  );
}