import React, { useState } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Download, FileText, TrendingUp, Users, DollarSign, Zap, Calendar, Library, Clock, Coffee, Sparkles } from "lucide-react";
import StaffingCostReport from "@/components/reports/StaffingCostReport";
import StaffPerformanceReport from "@/components/reports/StaffPerformanceReport";
import ClientTrendsReport from "@/components/reports/ClientTrendsReport";
import OperationalEfficiencyReport from "@/components/reports/OperationalEfficiencyReport";
import CustomReportBuilder from "@/components/reports/CustomReportBuilder";
import ReportTemplateLibrary from "@/components/reports/ReportTemplateLibrary";
import ScheduledReports from "@/components/reports/ScheduledReports";
import ReportExporter from "@/components/reports/ReportExporter";
import { useToast } from "@/components/ui/use-toast";

export default function Reports() {
  const [activeTab, setActiveTab] = useState("templates");
  const [showExporter, setShowExporter] = useState(false);
  const [exportReportName, setExportReportName] = useState("");
  const [exportData, setExportData] = useState(null);
  const { toast } = useToast();

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

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

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

  const { data: invoices = [] } = useQuery({
    queryKey: ['invoices-reports'],
    queryFn: () => base44.entities.Invoice.list(),
    initialData: [],
  });

  const { data: vendors = [] } = useQuery({
    queryKey: ['vendors-reports'],
    queryFn: () => base44.entities.Vendor.list(),
    initialData: [],
  });

  const userRole = user?.user_role || user?.role || 'admin';
  const scheduledReports = user?.scheduled_reports || [];

  const handleSelectTemplate = (template) => {
    setExportReportName(template.name);
    setExportData({ 
      template: template.id, 
      events, 
      staff, 
      invoices,
      vendors,
      generated: new Date().toISOString() 
    });
    setShowExporter(true);
  };

  const handlePreviewTemplate = (template) => {
    toast({ 
      title: `Preview: ${template.name}`, 
      description: template.description 
    });
  };

  const handleExportAll = () => {
    const data = {
      events,
      staff,
      invoices,
      generated: new Date().toISOString(),
    };
    
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `krow-full-report-${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    toast({ title: "✅ Report Exported", description: "Full report downloaded successfully" });
  };

  return (
    <div className="p-4 md:p-8 bg-slate-50 min-h-screen">
      <div className="max-w-[1600px] mx-auto">
        {/* Hero Header - Compact */}
        <div className="bg-gradient-to-r from-[#1C323E] to-[#0A39DF] rounded-2xl p-5 mb-6 text-white">
          <div className="flex items-center justify-between flex-wrap gap-4">
            <div className="flex items-center gap-3">
              <div className="w-12 h-12 bg-white/10 rounded-xl flex items-center justify-center backdrop-blur-sm">
                <FileText className="w-6 h-6" />
              </div>
              <div>
                <h1 className="text-xl font-bold">On-Demand Reporting Suite</h1>
                <p className="text-white/70 text-sm">Intelligence that drives decisions</p>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <div className="hidden md:flex items-center gap-3 mr-4">
                <div className="text-center px-3">
                  <p className="text-2xl font-bold">{events.length}</p>
                  <p className="text-[10px] text-white/60 uppercase">Events</p>
                </div>
                <div className="w-px h-8 bg-white/20" />
                <div className="text-center px-3">
                  <p className="text-2xl font-bold">{staff.length}</p>
                  <p className="text-[10px] text-white/60 uppercase">Staff</p>
                </div>
                <div className="w-px h-8 bg-white/20" />
                <div className="text-center px-3">
                  <p className="text-2xl font-bold">${(invoices.reduce((s, i) => s + (i.amount || 0), 0) / 1000).toFixed(0)}K</p>
                  <p className="text-[10px] text-white/60 uppercase">Revenue</p>
                </div>
              </div>
              <Button onClick={handleExportAll} size="sm" className="bg-white text-[#0A39DF] hover:bg-white/90 font-semibold">
                <Download className="w-4 h-4 mr-1" />
                Export All
              </Button>
            </div>
          </div>
        </div>

        {/* Quick Actions - Horizontal Chips */}
        <div className="flex items-center gap-2 mb-5 overflow-x-auto pb-1">
          <span className="text-xs text-slate-500 font-medium whitespace-nowrap">Quick:</span>
          <Button 
            size="sm" 
            className="bg-emerald-600 hover:bg-emerald-700 h-8 text-xs whitespace-nowrap"
            onClick={() => { setExportReportName('Weekly Labor Summary'); setExportData({ events, staff, invoices }); setShowExporter(true); }}
          >
            <Download className="w-3 h-3 mr-1" />
            Labor Summary
          </Button>
          <Button 
            size="sm" 
            variant="outline"
            className="h-8 text-xs whitespace-nowrap"
            onClick={() => { setExportReportName('Vendor Scorecard'); setExportData({ vendors, events }); setShowExporter(true); }}
          >
            <TrendingUp className="w-3 h-3 mr-1" />
            Vendor Scorecard
          </Button>
          <Button 
            size="sm" 
            variant="outline"
            className="h-8 text-xs whitespace-nowrap"
            onClick={() => { setExportReportName('Compliance Report'); setExportData({ staff, events }); setShowExporter(true); }}
          >
            <Users className="w-3 h-3 mr-1" />
            Compliance
          </Button>
          <Button 
            size="sm" 
            variant="outline"
            className="h-8 text-xs whitespace-nowrap"
            onClick={() => { setExportReportName('Invoice Aging'); setExportData({ invoices }); setShowExporter(true); }}
          >
            <FileText className="w-3 h-3 mr-1" />
            Invoice Aging
          </Button>
          <Button 
            size="sm" 
            variant="outline"
            className="h-8 text-xs whitespace-nowrap"
            onClick={() => { setExportReportName('Payroll Summary'); setExportData({ staff, events, invoices }); setShowExporter(true); }}
          >
            <DollarSign className="w-3 h-3 mr-1" />
            Payroll
          </Button>
        </div>

        {/* Report Tabs - Clean Design */}
        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <div className="bg-white rounded-xl border shadow-sm p-1 mb-6">
            <TabsList className="bg-transparent p-0 h-auto flex flex-wrap gap-1">
              <TabsTrigger value="templates" className="data-[state=active]:bg-[#0A39DF] data-[state=active]:text-white rounded-lg px-4 py-2">
                <Library className="w-4 h-4 mr-1.5" />
                Templates
              </TabsTrigger>
              <TabsTrigger value="scheduled" className="data-[state=active]:bg-[#0A39DF] data-[state=active]:text-white rounded-lg px-4 py-2">
                <Clock className="w-4 h-4 mr-1.5" />
                Scheduled
                {scheduledReports.length > 0 && (
                  <Badge className="ml-1.5 bg-purple-100 text-purple-700 h-5 px-1.5 text-[10px]">{scheduledReports.length}</Badge>
                )}
              </TabsTrigger>
              <div className="w-px h-6 bg-slate-200 mx-1 self-center" />
              <TabsTrigger value="costs" className="data-[state=active]:bg-[#0A39DF] data-[state=active]:text-white rounded-lg px-4 py-2">
                <DollarSign className="w-4 h-4 mr-1.5" />
                Labor Spend
              </TabsTrigger>
              <TabsTrigger value="performance" className="data-[state=active]:bg-[#0A39DF] data-[state=active]:text-white rounded-lg px-4 py-2">
                <TrendingUp className="w-4 h-4 mr-1.5" />
                Performance
              </TabsTrigger>
              <TabsTrigger value="clients" className="data-[state=active]:bg-[#0A39DF] data-[state=active]:text-white rounded-lg px-4 py-2">
                <Users className="w-4 h-4 mr-1.5" />
                Clients
              </TabsTrigger>
              <TabsTrigger value="efficiency" className="data-[state=active]:bg-[#0A39DF] data-[state=active]:text-white rounded-lg px-4 py-2">
                <Zap className="w-4 h-4 mr-1.5" />
                Efficiency
              </TabsTrigger>
              <div className="w-px h-6 bg-slate-200 mx-1 self-center" />
              <TabsTrigger value="custom" className="data-[state=active]:bg-[#0A39DF] data-[state=active]:text-white rounded-lg px-4 py-2">
                <Sparkles className="w-4 h-4 mr-1.5" />
                Custom Builder
              </TabsTrigger>
            </TabsList>
          </div>

          <TabsContent value="templates" className="mt-6">
            <ReportTemplateLibrary 
              userRole={userRole}
              onSelectTemplate={handleSelectTemplate}
              onPreview={handlePreviewTemplate}
            />
          </TabsContent>

          <TabsContent value="scheduled" className="mt-6">
            <ScheduledReports 
              userRole={userRole}
              scheduledReports={scheduledReports}
              onUpdate={refetchUser}
            />
          </TabsContent>

          <TabsContent value="costs" className="mt-6">
            <StaffingCostReport events={events} invoices={invoices} userRole={userRole} />
          </TabsContent>

          <TabsContent value="performance" className="mt-6">
            <StaffPerformanceReport staff={staff} events={events} userRole={userRole} />
          </TabsContent>

          <TabsContent value="clients" className="mt-6">
            <ClientTrendsReport events={events} invoices={invoices} userRole={userRole} />
          </TabsContent>

          <TabsContent value="efficiency" className="mt-6">
            <OperationalEfficiencyReport events={events} staff={staff} userRole={userRole} />
          </TabsContent>

          <TabsContent value="custom" className="mt-6">
            <CustomReportBuilder events={events} staff={staff} invoices={invoices} />
          </TabsContent>
        </Tabs>

        {/* Export Modal */}
        <ReportExporter
          open={showExporter}
          onClose={() => setShowExporter(false)}
          reportName={exportReportName}
          reportData={exportData}
        />
      </div>
    </div>
  );
}