"use client"

import Link from "next/link"
import {
  useClubStatsQuery,
  useRecentDistributionsQuery,
} from "@/services/dashboard"
import { useTranslations } from "next-intl"
import {
  Bar,
  BarChart,
  Cell,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts"
import { Leaf, Package, Plus, TrendingUp, UserPlus, Users } from "lucide-react"

import {
  mockClubStats,
  mockRecentDistributions,
  mockStockByStrain,
} from "@/data/mock/dashboard"

import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { CardSkeleton, TableSkeleton } from "@/components/ui/data-skeleton"

export default function DashboardPage() {
  const t = useTranslations("dashboard")

  const { data: statsData, isLoading: statsLoading } = useClubStatsQuery()
  const { data: distributionsData, isLoading: distributionsLoading } =
    useRecentDistributionsQuery()

  // Fallback to mock data when backend unavailable
  const stats = statsData ?? mockClubStats
  const recentDistributions = distributionsData ?? mockRecentDistributions

  const chartData = mockStockByStrain.map((batch) => ({
    name: batch.strainName,
    grams: batch.availableGrams,
  }))

  return (
    <div className="flex flex-col gap-6 p-4 md:p-6">
      {/* KPI Cards */}
      {statsLoading ? (
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
          <CardSkeleton />
          <CardSkeleton />
          <CardSkeleton />
          <CardSkeleton />
        </div>
      ) : (
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
          {/* Active Members */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                {t("activeMembers")}
              </CardTitle>
              <Users className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats.activeMembers}</div>
              <p className="text-xs text-muted-foreground">
                {t("trend", { value: "12" })}
              </p>
            </CardContent>
          </Card>

          {/* Distributions Today */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                {t("distributionsToday")}
              </CardTitle>
              <Leaf className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {stats.distributionsToday}
              </div>
              <p className="text-xs text-muted-foreground">
                {t("distributionCount", {
                  count: stats.distributionsToday,
                  grams: stats.gramsDistributedToday,
                })}
              </p>
            </CardContent>
          </Card>

          {/* Stock Level */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                {t("stockLevel")}
              </CardTitle>
              <Package className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {stats.totalStockGrams.toLocaleString("de-DE")}
                {t("grams")}
              </div>
              <p className="text-xs text-muted-foreground">
                {mockStockByStrain.length} Sorten verfügbar
              </p>
            </CardContent>
          </Card>

          {/* Monthly Quota */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                {t("monthlyQuota")}
              </CardTitle>
              <TrendingUp className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {stats.monthlyQuotaUsagePercent}%
              </div>
              <p className="text-xs text-muted-foreground">
                {t("quotaUsed", {
                  value: stats.monthlyQuotaUsagePercent,
                })}
              </p>
            </CardContent>
          </Card>
        </div>
      )}

      {/* Quick Actions */}
      <Card>
        <CardHeader>
          <CardTitle>{t("quickActions")}</CardTitle>
        </CardHeader>
        <CardContent className="flex flex-wrap gap-3">
          <Button
            asChild
            className="bg-green-600 hover:bg-green-700 dark:bg-green-700 dark:hover:bg-green-600"
          >
            <Link href="/distributions/new">
              <Plus className="mr-2 h-4 w-4" />
              {t("newDistribution")}
            </Link>
          </Button>
          <Button
            asChild
            variant="outline"
            className="border-green-600 text-green-700 hover:bg-green-50 dark:border-green-500 dark:text-green-400 dark:hover:bg-green-950"
          >
            <Link href="/members/new">
              <UserPlus className="mr-2 h-4 w-4" />
              {t("addMember")}
            </Link>
          </Button>
        </CardContent>
      </Card>

      {/* Bottom section: Table + Chart */}
      <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
        {/* Recent Distributions Table */}
        <Card>
          <CardHeader>
            <CardTitle>{t("recentDistributions")}</CardTitle>
          </CardHeader>
          <CardContent>
            {distributionsLoading ? (
              <TableSkeleton rows={5} columns={5} />
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b text-left text-muted-foreground">
                      <th className="pb-2 font-medium">{t("date")}</th>
                      <th className="pb-2 font-medium">{t("member")}</th>
                      <th className="pb-2 font-medium">{t("strain")}</th>
                      <th className="pb-2 font-medium">{t("amount")}</th>
                      <th className="pb-2 font-medium">{t("staff")}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {recentDistributions.map((dist) => (
                      <tr key={dist.id} className="border-b last:border-0">
                        <td className="py-2">
                          {new Date(dist.recordedAt).toLocaleTimeString(
                            "de-DE",
                            {
                              hour: "2-digit",
                              minute: "2-digit",
                            }
                          )}
                        </td>
                        <td className="py-2">{dist.memberName}</td>
                        <td className="py-2">{dist.strainName}</td>
                        <td className="py-2">{dist.amountGrams}g</td>
                        <td className="py-2">{dist.recordedBy}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Stock Level Chart */}
        <Card>
          <CardHeader>
            <CardTitle>{t("stockByStrain")}</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="h-[300px] w-full">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart
                  data={chartData}
                  margin={{ top: 5, right: 20, left: 10, bottom: 60 }}
                >
                  <XAxis
                    dataKey="name"
                    angle={-45}
                    textAnchor="end"
                    height={80}
                    tick={{ fontSize: 12 }}
                    className="fill-muted-foreground"
                  />
                  <YAxis
                    tick={{ fontSize: 12 }}
                    className="fill-muted-foreground"
                  />
                  <Tooltip
                    contentStyle={{
                      backgroundColor: "hsl(var(--card))",
                      border: "1px solid hsl(var(--border))",
                      borderRadius: "8px",
                      color: "hsl(var(--card-foreground))",
                    }}
                    formatter={(value) => [`${value}g`, "Bestand"]}
                  />
                  <Bar dataKey="grams" radius={[4, 4, 0, 0]}>
                    {chartData.map((_, index) => (
                      <Cell
                        key={`cell-${index}`}
                        className="fill-green-600 dark:fill-green-500"
                      />
                    ))}
                  </Bar>
                </BarChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
