import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  LineChart,
  Line,
  PieChart,
  Pie,
  Cell,
} from "recharts";
import { Loader2 } from "lucide-react";
import AiReportNarrative from "@/components/ai/AiReportNarrative";
import { reportsService } from "@/services/reports.service";

const thresholds = ["0%", "50%", "70%", "90%"];

export default function StatsCorporatePage() {
  const [threshold, setThreshold] = useState("0%");
  const [entityId, setEntityId] = useState("all");

  const { data: filters } = useQuery({
    queryKey: ["reports-filters"],
    queryFn: () => reportsService.filters(),
  });

  const { data, isLoading } = useQuery({
    queryKey: ["stats-corporate", threshold, entityId],
    queryFn: () =>
      reportsService.statsCorporate({
        entity_id: entityId === "all" ? undefined : Number(entityId),
        threshold: Number(threshold.replace("%", "")),
        months: 6,
      }),
  });

  const barData = data?.by_module ?? [];
  const trendData = data?.trend ?? [];
  const distData = data?.distribution ?? [];
  const comparison = data?.comparison ?? [];
  const attemptsConsidered = data?.meta.attempts_considered ?? 0;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">
          Corporate Statistics
        </h1>
        <p className="text-muted-foreground">
          Entity-level performance analytics and reports.
          {data && (
            <span className="ml-2 text-xs">
              ({attemptsConsidered} scored attempts)
            </span>
          )}
        </p>
      </div>

      <div className="flex flex-wrap gap-3 items-center">
        <div className="flex gap-1">
          {thresholds.map((t) => (
            <Button
              key={t}
              variant={threshold === t ? "default" : "outline"}
              size="sm"
              onClick={() => setThreshold(t)}
            >
              {t}
            </Button>
          ))}
        </div>
        <Select value={entityId} onValueChange={setEntityId}>
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder="All Entities" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Entities</SelectItem>
            {filters?.entities.map((e) => (
              <SelectItem key={e.id} value={String(e.id)}>
                {e.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {isLoading ? (
        <div className="flex items-center justify-center p-12 text-muted-foreground">
          <Loader2 className="h-5 w-5 animate-spin mr-2" /> Aggregating
          attempts...
        </div>
      ) : attemptsConsidered === 0 ? (
        <Card className="border-0 shadow-sm">
          <CardContent className="p-8 text-center text-muted-foreground">
            No scored attempts match this threshold / entity combination yet.
          </CardContent>
        </Card>
      ) : (
        <Tabs defaultValue="overview">
          <TabsList>
            <TabsTrigger value="overview">Overview</TabsTrigger>
            <TabsTrigger value="trends">Trends</TabsTrigger>
            <TabsTrigger value="distribution">Distribution</TabsTrigger>
            <TabsTrigger value="comparison">Comparison</TabsTrigger>
          </TabsList>

          <TabsContent value="overview" className="mt-4">
            <AiReportNarrative
              report_type="corporate-overview"
              data={{ modules: barData }}
            />
            <Card className="border-0 shadow-sm">
              <CardHeader>
                <CardTitle className="text-base">
                  Average Score by Module
                </CardTitle>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={300}>
                  <BarChart data={barData}>
                    <CartesianGrid
                      strokeDasharray="3 3"
                      stroke="hsl(220, 16%, 90%)"
                    />
                    <XAxis dataKey="module" />
                    <YAxis domain={[0, 100]} />
                    <Tooltip />
                    <Bar
                      dataKey="score"
                      fill="hsl(243, 75%, 59%)"
                      radius={[4, 4, 0, 0]}
                    />
                  </BarChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="trends" className="mt-4">
            <AiReportNarrative
              report_type="corporate-trends"
              data={{ trends: trendData }}
            />
            <Card className="border-0 shadow-sm">
              <CardHeader>
                <CardTitle className="text-base">
                  Score Trend Over Time
                </CardTitle>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={300}>
                  <LineChart data={trendData}>
                    <CartesianGrid
                      strokeDasharray="3 3"
                      stroke="hsl(220, 16%, 90%)"
                    />
                    <XAxis dataKey="month" />
                    <YAxis domain={[0, 100]} />
                    <Tooltip />
                    <Line
                      type="monotone"
                      dataKey="avg"
                      stroke="hsl(243, 75%, 59%)"
                      strokeWidth={2}
                      dot={{ r: 4 }}
                    />
                  </LineChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="distribution" className="mt-4">
            <AiReportNarrative
              report_type="corporate-distribution"
              data={{ distribution: distData }}
            />
            <Card className="border-0 shadow-sm">
              <CardHeader>
                <CardTitle className="text-base">Level Distribution</CardTitle>
              </CardHeader>
              <CardContent className="flex justify-center">
                <ResponsiveContainer width="100%" height={300}>
                  <PieChart>
                    <Pie
                      data={distData}
                      dataKey="value"
                      nameKey="name"
                      cx="50%"
                      cy="50%"
                      outerRadius={100}
                      label
                    >
                      {distData.map((entry, i) => (
                        <Cell key={i} fill={entry.color} />
                      ))}
                    </Pie>
                    <Tooltip />
                  </PieChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="comparison" className="mt-4">
            <AiReportNarrative
              report_type="corporate-comparison"
              data={{ threshold, entities: comparison }}
            />
            <Card className="border-0 shadow-sm">
              <CardHeader>
                <CardTitle className="text-base">
                  Entity Comparison (average band × 10)
                </CardTitle>
              </CardHeader>
              <CardContent>
                {comparison.length === 0 ? (
                  <p className="text-center text-muted-foreground p-8">
                    No entities have attempts above this threshold.
                  </p>
                ) : (
                  <ResponsiveContainer width="100%" height={300}>
                    <BarChart data={comparison}>
                      <CartesianGrid
                        strokeDasharray="3 3"
                        stroke="hsl(220, 16%, 90%)"
                      />
                      <XAxis dataKey="entity_name" />
                      <YAxis domain={[0, 100]} />
                      <Tooltip />
                      <Bar
                        dataKey="avg"
                        fill="hsl(142, 71%, 45%)"
                        radius={[4, 4, 0, 0]}
                      />
                    </BarChart>
                  </ResponsiveContainer>
                )}
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      )}
    </div>
  );
}
