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 { Download, FileText, TrendingUp, Users, DollarSign, Zap } 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 { useToast } from "@/components/ui/use-toast";

export default function Reports() {
  const [activeTab, setActiveTab] = useState("costs");
  const { toast } = useToast();

  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 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-7xl mx-auto">
        <div className="flex items-center justify-between mb-6">
          <div>
            <h1 className="text-2xl font-bold text-slate-900">Reports & Analytics</h1>
            <p className="text-sm text-slate-500 mt-1">
              Comprehensive insights into staffing, costs, and performance
            </p>
          </div>
          <Button onClick={handleExportAll} className="bg-[#0A39DF]">
            <Download className="w-4 h-4 mr-2" />
            Export All Data
          </Button>
        </div>

        {/* Quick Stats */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
          <Card className="border-blue-200 bg-blue-50">
            <CardContent className="pt-6">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-blue-500 rounded-lg flex items-center justify-center">
                  <FileText className="w-5 h-5 text-white" />
                </div>
                <div>
                  <p className="text-xs text-blue-600 font-semibold uppercase">Total Events</p>
                  <p className="text-2xl font-bold text-blue-700">{events.length}</p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="border-green-200 bg-green-50">
            <CardContent className="pt-6">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-green-500 rounded-lg flex items-center justify-center">
                  <Users className="w-5 h-5 text-white" />
                </div>
                <div>
                  <p className="text-xs text-green-600 font-semibold uppercase">Active Staff</p>
                  <p className="text-2xl font-bold text-green-700">{staff.length}</p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="border-purple-200 bg-purple-50">
            <CardContent className="pt-6">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-purple-500 rounded-lg flex items-center justify-center">
                  <DollarSign className="w-5 h-5 text-white" />
                </div>
                <div>
                  <p className="text-xs text-purple-600 font-semibold uppercase">Total Revenue</p>
                  <p className="text-2xl font-bold text-purple-700">
                    ${invoices.reduce((sum, inv) => sum + (inv.amount || 0), 0).toLocaleString()}
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="border-amber-200 bg-amber-50">
            <CardContent className="pt-6">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-amber-500 rounded-lg flex items-center justify-center">
                  <Zap className="w-5 h-5 text-white" />
                </div>
                <div>
                  <p className="text-xs text-amber-600 font-semibold uppercase">Automation</p>
                  <p className="text-2xl font-bold text-amber-700">85%</p>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Report Tabs */}
        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList className="bg-white border">
            <TabsTrigger value="costs">
              <DollarSign className="w-4 h-4 mr-2" />
              Staffing Costs
            </TabsTrigger>
            <TabsTrigger value="performance">
              <TrendingUp className="w-4 h-4 mr-2" />
              Staff Performance
            </TabsTrigger>
            <TabsTrigger value="clients">
              <Users className="w-4 h-4 mr-2" />
              Client Trends
            </TabsTrigger>
            <TabsTrigger value="efficiency">
              <Zap className="w-4 h-4 mr-2" />
              Operational Efficiency
            </TabsTrigger>
            <TabsTrigger value="custom">
              <FileText className="w-4 h-4 mr-2" />
              Custom Reports
            </TabsTrigger>
          </TabsList>

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

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

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

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

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