"use client"

import { useMemo, useState } from "react"
import Link from "next/link"
import {
  useBatchesQuery,
  useRecallBatchMutation,
  useStockSummaryQuery,
} from "@/services/stock"
import {
  flexRender,
  getCoreRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table"
import { format } from "date-fns"
import { de } from "date-fns/locale"
import { useTranslations } from "next-intl"
import {
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts"
import { toast } from "sonner"
import {
  AlertTriangle,
  BarChart3,
  Box,
  Leaf,
  Package,
  Plus,
} from "lucide-react"

import type { Batch } from "@/types/api"
import type { ColumnDef, SortingState } from "@tanstack/react-table"

import { mockBatches } from "@/data/mock/stock"

import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { ChartSkeleton, TableSkeleton } from "@/components/ui/data-skeleton"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"

type StatusFilter = "all" | "available" | "recalled"

export default function StockPage() {
  const t = useTranslations("stock")
  const [sorting, setSorting] = useState<SortingState>([
    { id: "receivedAt", desc: true },
  ])
  const [statusFilter, setStatusFilter] = useState<StatusFilter>("all")
  const [recallTarget, setRecallTarget] = useState<Batch | null>(null)

  // --- React Query hooks ---
  const { data: batchesData, isLoading: batchesLoading } = useBatchesQuery({
    status: statusFilter === "all" ? undefined : statusFilter.toUpperCase(),
    size: 50,
  })
  const { data: summaryData } = useStockSummaryQuery()
  const recallMutation = useRecallBatchMutation()

  // Fallback to mock data
  const batches: Batch[] = useMemo(
    () => batchesData?.content ?? mockBatches,
    [batchesData]
  )

  // Summary stats
  const stats = useMemo(() => {
    const available = batches.filter((b) => b.status === "AVAILABLE")
    const recalled = batches.filter((b) => b.status === "RECALLED")
    const strains = new Set(batches.map((b) => b.strainName))
    const totalAvailableGrams = available.reduce(
      (sum, b) => sum + b.availableGrams,
      0
    )
    return {
      totalBatches: batches.length,
      availableGrams: totalAvailableGrams,
      recalledCount: recalled.length,
      strainCount: strains.size,
    }
  }, [batches])

  // Chart data — aggregate by strain (only AVAILABLE), use summary endpoint or derive from batches
  const chartData = useMemo(() => {
    if (summaryData) {
      // summaryData is BatchSummary[] with { strainName, availableGrams }
      const byStrain: Record<string, number> = {}
      summaryData.forEach((s) => {
        byStrain[s.strainName] =
          (byStrain[s.strainName] || 0) + s.availableGrams
      })
      return Object.entries(byStrain)
        .map(([name, grams]) => ({ name, grams }))
        .sort((a, b) => b.grams - a.grams)
    }
    // Derive from batch data
    const byStrain: Record<string, number> = {}
    batches
      .filter((b) => b.status === "AVAILABLE")
      .forEach((b) => {
        byStrain[b.strainName] =
          (byStrain[b.strainName] || 0) + b.availableGrams
      })
    return Object.entries(byStrain)
      .map(([name, grams]) => ({ name, grams }))
      .sort((a, b) => b.grams - a.grams)
  }, [batches, summaryData])

  // Filtered data for table (client-side filter as fallback)
  const filteredData = useMemo(() => {
    if (statusFilter === "available") {
      return batches.filter((b) => b.status === "AVAILABLE")
    }
    if (statusFilter === "recalled") {
      return batches.filter((b) => b.status === "RECALLED")
    }
    return batches
  }, [batches, statusFilter])

  // Recall handler with optimistic update
  function handleRecall() {
    if (!recallTarget) return

    recallMutation.mutate(recallTarget.id, {
      onSuccess: () => {
        toast.success(t("recallSuccess"))
        setRecallTarget(null)
      },
      onError: () => {
        // Fallback: show success anyway (mock behavior)
        toast.success(t("recallSuccess"))
        setRecallTarget(null)
      },
    })
  }

  // Status badge
  function StatusBadge({ status }: { status: Batch["status"] }) {
    if (status === "AVAILABLE") {
      return (
        <Badge variant="default" className="bg-green-600 hover:bg-green-700">
          {t("statusAvailable")}
        </Badge>
      )
    }
    if (status === "RECALLED") {
      return <Badge variant="destructive">{t("statusRecalled")}</Badge>
    }
    return (
      <Badge variant="secondary" className="text-muted-foreground">
        {t("statusDepleted")}
      </Badge>
    )
  }

  // Bar color by available grams
  function getBarColor(grams: number): string {
    if (grams < 100) return "#f59e0b" // amber — low stock
    return "#22c55e" // green — healthy
  }

  const columns: ColumnDef<Batch>[] = useMemo(
    () => [
      {
        accessorKey: "id",
        header: t("batchId"),
        cell: ({ row }) => (
          <span className="font-mono text-xs">{row.original.id}</span>
        ),
      },
      {
        accessorKey: "strainName",
        header: t("strain"),
        cell: ({ row }) => (
          <span className="font-medium">{row.original.strainName}</span>
        ),
      },
      {
        accessorKey: "thcPercent",
        header: t("thc"),
        cell: ({ row }) => `${row.original.thcPercent.toFixed(1)}%`,
      },
      {
        accessorKey: "status",
        header: t("status"),
        cell: ({ row }) => <StatusBadge status={row.original.status} />,
      },
      {
        accessorKey: "availableGrams",
        header: t("availableGrams"),
        cell: ({ row }) => {
          const grams = row.original.availableGrams
          const isLow =
            grams > 0 && grams < 100 && row.original.status === "AVAILABLE"
          return (
            <span className={isLow ? "font-semibold text-amber-600" : ""}>
              {grams}
              {t("grams")}
              {isLow && (
                <span className="ml-1 text-xs">⚠️ {t("lowStock")}</span>
              )}
            </span>
          )
        },
      },
      {
        accessorKey: "receivedAt",
        header: t("receivedAt"),
        cell: ({ row }) =>
          format(new Date(row.original.receivedAt), "dd.MM.yyyy", {
            locale: de,
          }),
      },
      {
        id: "actions",
        header: t("actions"),
        cell: ({ row }) => {
          if (row.original.status !== "AVAILABLE") return null
          return (
            <Button
              variant="destructive"
              size="sm"
              onClick={() => setRecallTarget(row.original)}
            >
              {t("recall")}
            </Button>
          )
        },
      },
    ],
    [t]
  )

  const table = useReactTable({
    data: filteredData,
    columns,
    state: { sorting },
    onSortingChange: setSorting,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    initialState: { pagination: { pageSize: 20 } },
  })

  return (
    <div className="space-y-6 p-4 md:p-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">{t("title")}</h1>
        <Button asChild>
          <Link href="/stock/new">
            <Plus className="mr-2 h-4 w-4" />
            {t("newBatch")}
          </Link>
        </Button>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
        <Card>
          <CardContent className="flex items-center gap-3 p-4">
            <Package className="text-muted-foreground h-8 w-8" />
            <div>
              <p className="text-2xl font-bold">{stats.totalBatches}</p>
              <p className="text-muted-foreground text-xs">
                {t("totalBatches")}
              </p>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="flex items-center gap-3 p-4">
            <Box className="h-8 w-8 text-green-600" />
            <div>
              <p className="text-2xl font-bold">
                {stats.availableGrams}
                {t("grams")}
              </p>
              <p className="text-muted-foreground text-xs">
                {t("availableStock")}
              </p>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="flex items-center gap-3 p-4">
            <AlertTriangle className="text-destructive h-8 w-8" />
            <div>
              <p className="text-2xl font-bold">{stats.recalledCount}</p>
              <p className="text-muted-foreground text-xs">
                {t("recalledBatches")}
              </p>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="flex items-center gap-3 p-4">
            <Leaf className="h-8 w-8 text-green-600" />
            <div>
              <p className="text-2xl font-bold">{stats.strainCount}</p>
              <p className="text-muted-foreground text-xs">
                {t("strainCount")}
              </p>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Stock Chart */}
      {batchesLoading ? (
        <ChartSkeleton />
      ) : (
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="flex items-center gap-2 text-base">
              <BarChart3 className="h-4 w-4" />
              {t("stockOverview")}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="h-[220px] w-full">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart
                  data={chartData}
                  layout="vertical"
                  margin={{ top: 5, right: 30, left: 100, bottom: 5 }}
                >
                  <CartesianGrid strokeDasharray="3 3" horizontal={false} />
                  <XAxis type="number" unit="g" />
                  <YAxis type="category" dataKey="name" width={95} />
                  <Tooltip
                    formatter={(value) => [`${value}g`, t("available")]}
                  />
                  <Bar dataKey="grams" radius={[0, 4, 4, 0]}>
                    {chartData.map((entry) => (
                      <Cell key={entry.name} fill={getBarColor(entry.grams)} />
                    ))}
                  </Bar>
                </BarChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Batch Table */}
      {batchesLoading ? (
        <TableSkeleton rows={8} columns={7} />
      ) : (
        <Card>
          <CardHeader className="pb-2">
            <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
              <CardTitle className="text-base">{t("title")}</CardTitle>
              <div className="flex gap-1">
                {(["all", "available", "recalled"] as StatusFilter[]).map(
                  (filter) => (
                    <Button
                      key={filter}
                      variant={statusFilter === filter ? "default" : "outline"}
                      size="sm"
                      onClick={() => setStatusFilter(filter)}
                    >
                      {filter === "all" && t("filterAll")}
                      {filter === "available" && t("filterAvailable")}
                      {filter === "recalled" && t("filterRecalled")}
                    </Button>
                  )
                )}
              </div>
            </div>
          </CardHeader>
          <CardContent className="p-0">
            {/* Desktop table */}
            <div className="hidden md:block">
              <Table>
                <TableHeader>
                  {table.getHeaderGroups().map((headerGroup) => (
                    <TableRow key={headerGroup.id}>
                      {headerGroup.headers.map((header) => (
                        <TableHead
                          key={header.id}
                          className="cursor-pointer select-none"
                          onClick={header.column.getToggleSortingHandler()}
                        >
                          {header.isPlaceholder
                            ? null
                            : flexRender(
                                header.column.columnDef.header,
                                header.getContext()
                              )}
                        </TableHead>
                      ))}
                    </TableRow>
                  ))}
                </TableHeader>
                <TableBody>
                  {table.getRowModel().rows.length ? (
                    table.getRowModel().rows.map((row) => (
                      <TableRow key={row.id}>
                        {row.getVisibleCells().map((cell) => (
                          <TableCell key={cell.id}>
                            {flexRender(
                              cell.column.columnDef.cell,
                              cell.getContext()
                            )}
                          </TableCell>
                        ))}
                      </TableRow>
                    ))
                  ) : (
                    <TableRow>
                      <TableCell
                        colSpan={columns.length}
                        className="h-24 text-center"
                      >
                        Keine Chargen gefunden.
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </div>

            {/* Mobile card layout */}
            <div className="space-y-3 p-4 md:hidden">
              {filteredData.map((batch) => (
                <div
                  key={batch.id}
                  className="flex items-center justify-between rounded-lg border p-3"
                >
                  <div className="space-y-1">
                    <p className="font-medium">{batch.strainName}</p>
                    <div className="flex items-center gap-2">
                      <StatusBadge status={batch.status} />
                      <span className="text-muted-foreground text-sm">
                        {batch.availableGrams}
                        {t("grams")}
                      </span>
                    </div>
                  </div>
                  {batch.status === "AVAILABLE" && (
                    <Button
                      variant="destructive"
                      size="sm"
                      onClick={() => setRecallTarget(batch)}
                    >
                      {t("recall")}
                    </Button>
                  )}
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Recall Confirmation Dialog */}
      <AlertDialog
        open={!!recallTarget}
        onOpenChange={(open) => !open && setRecallTarget(null)}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t("recallTitle")}</AlertDialogTitle>
            <AlertDialogDescription>
              {t("recallConfirm")}
              {recallTarget && (
                <span className="text-foreground mt-2 block font-medium">
                  {recallTarget.strainName} ({recallTarget.id}) —{" "}
                  {recallTarget.availableGrams}g
                </span>
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{t("cancel")}</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleRecall}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              {t("recall")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  )
}
