"use client"

import { useState } from "react"
import {
  downloadMemberListPdf,
  downloadMonthlyReportCsv,
  downloadMonthlyReportPdf,
  downloadRecallReportPdf,
  useMemberListReportQuery,
  useMonthlyReportQuery,
  useRecallReportQuery,
} from "@/services/reports"
import { useTranslations } from "next-intl"
import { toast } from "sonner"
import {
  AlertTriangle,
  CalendarDays,
  Download,
  Eye,
  FileText,
  Info,
  Users,
} from "lucide-react"

import {
  mockMemberListPreview,
  mockMonthlyReportPreview,
  mockRecallReportPreview,
} from "@/data/mock/reports"

import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Select } from "@/components/ui/select"
import {
  Sheet,
  SheetClose,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"
import { Skeleton } from "@/components/ui/skeleton"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"

type ReportType = "monthly" | "memberList" | "recall"

export default function ReportsPage() {
  const t = useTranslations("reports")

  // Controls state
  const [selectedMonth, setSelectedMonth] = useState("2026-06")
  const [statusFilter, setStatusFilter] = useState("all")
  const [dateFrom, setDateFrom] = useState("2026-05-01")
  const [dateTo, setDateTo] = useState("2026-06-12")

  // Preview state
  const [previewOpen, setPreviewOpen] = useState(false)
  const [previewType, setPreviewType] = useState<ReportType>("monthly")

  // React Query hooks
  const monthlyQuery = useMonthlyReportQuery(selectedMonth)
  const memberListQuery = useMemberListReportQuery(
    statusFilter === "all" ? undefined : statusFilter
  )
  const recallQuery = useRecallReportQuery(
    dateFrom && dateTo ? { from: dateFrom, to: dateTo } : undefined
  )

  const handleDownload = async (
    reportType: ReportType,
    format: "pdf" | "csv"
  ) => {
    toast.info(t("generating"))

    try {
      if (reportType === "monthly" && format === "pdf") {
        await downloadMonthlyReportPdf(selectedMonth)
      } else if (reportType === "monthly" && format === "csv") {
        await downloadMonthlyReportCsv(selectedMonth)
      } else if (reportType === "memberList" && format === "pdf") {
        await downloadMemberListPdf(
          statusFilter === "all" ? undefined : statusFilter
        )
      } else if (reportType === "recall" && format === "pdf") {
        await downloadRecallReportPdf(dateFrom, dateTo)
      } else {
        // Fallback: formats not yet wired to backend
        const names: Record<ReportType, string> = {
          monthly: t("monthly"),
          memberList: t("memberList"),
          recall: t("recall"),
        }
        const monthLabel = selectedMonth.replace("-", " ")
        const fileName = `${names[reportType]} ${monthLabel}.${format}`
        setTimeout(() => {
          toast.success(t("downloaded", { name: fileName }))
        }, 1200)
        return
      }
      toast.success(t("downloaded", { name: `${reportType}.${format}` }))
    } catch {
      // If backend unavailable, fall back to mock toast
      const names: Record<ReportType, string> = {
        monthly: t("monthly"),
        memberList: t("memberList"),
        recall: t("recall"),
      }
      const monthLabel = selectedMonth.replace("-", " ")
      const fileName = `${names[reportType]} ${monthLabel}.${format}`
      setTimeout(() => {
        toast.success(t("downloaded", { name: fileName }))
      }, 1200)
    }
  }

  const handlePreview = (type: ReportType) => {
    setPreviewType(type)
    setPreviewOpen(true)
  }

  const monthOptions = [
    { value: "2026-06", label: "Juni 2026" },
    { value: "2026-05", label: "Mai 2026" },
    { value: "2026-04", label: "April 2026" },
    { value: "2026-03", label: "März 2026" },
    { value: "2026-02", label: "Februar 2026" },
    { value: "2026-01", label: "Januar 2026" },
  ]

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold tracking-tight">{t("title")}</h1>
      </div>

      {/* Audit Trail Notice */}
      <div className="bg-muted/50 border rounded-lg p-4 flex items-start gap-3">
        <Info className="h-5 w-5 text-muted-foreground mt-0.5 shrink-0" />
        <p className="text-sm text-muted-foreground">{t("auditTrail")}</p>
      </div>

      {/* Report Cards Grid */}
      <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
        {/* Card 1: Monthly Report */}
        <Card>
          <CardHeader className="pb-3">
            <div className="flex items-center gap-2">
              <CalendarDays className="h-5 w-5 text-primary" />
              <CardTitle className="text-lg">{t("monthly")}</CardTitle>
            </div>
          </CardHeader>
          <CardContent className="space-y-4">
            <p className="text-sm text-muted-foreground">{t("monthlyDesc")}</p>

            {/* Month picker */}
            <div className="space-y-1.5">
              <label className="text-sm font-medium">{t("selectMonth")}</label>
              <Select
                value={selectedMonth}
                onChange={(e) => setSelectedMonth(e.target.value)}
              >
                {monthOptions.map((opt) => (
                  <option key={opt.value} value={opt.value}>
                    {opt.label}
                  </option>
                ))}
              </Select>
            </div>

            {/* Action buttons */}
            <div className="flex flex-col gap-2">
              <Button
                variant="default"
                size="sm"
                className="w-full justify-start"
                onClick={() => handleDownload("monthly", "pdf")}
              >
                <Download className="mr-2 h-4 w-4" />
                {t("downloadPdf")}
              </Button>
              <Button
                variant="outline"
                size="sm"
                className="w-full justify-start"
                onClick={() => handleDownload("monthly", "csv")}
              >
                <FileText className="mr-2 h-4 w-4" />
                {t("downloadCsv")}
              </Button>
              <Button
                variant="ghost"
                size="sm"
                className="w-full justify-start"
                onClick={() => handlePreview("monthly")}
              >
                <Eye className="mr-2 h-4 w-4" />
                {t("preview")}
              </Button>
            </div>
          </CardContent>
        </Card>

        {/* Card 2: Member List Report */}
        <Card>
          <CardHeader className="pb-3">
            <div className="flex items-center gap-2">
              <Users className="h-5 w-5 text-primary" />
              <CardTitle className="text-lg">{t("memberList")}</CardTitle>
            </div>
          </CardHeader>
          <CardContent className="space-y-4">
            <p className="text-sm text-muted-foreground">
              {t("memberListDesc")}
            </p>

            {/* Status filter */}
            <div className="space-y-1.5">
              <label className="text-sm font-medium">{t("selectStatus")}</label>
              <Select
                value={statusFilter}
                onChange={(e) => setStatusFilter(e.target.value)}
              >
                <option value="all">{t("allStatuses")}</option>
                <option value="active">{t("activeOnly")}</option>
                <option value="suspended">{t("suspendedOnly")}</option>
              </Select>
            </div>

            {/* Action buttons */}
            <div className="flex flex-col gap-2">
              <Button
                variant="default"
                size="sm"
                className="w-full justify-start"
                onClick={() => handleDownload("memberList", "pdf")}
              >
                <Download className="mr-2 h-4 w-4" />
                {t("downloadPdf")}
              </Button>
              <Button
                variant="outline"
                size="sm"
                className="w-full justify-start"
                onClick={() => handleDownload("memberList", "csv")}
              >
                <FileText className="mr-2 h-4 w-4" />
                {t("downloadCsv")}
              </Button>
              <Button
                variant="ghost"
                size="sm"
                className="w-full justify-start"
                onClick={() => handlePreview("memberList")}
              >
                <Eye className="mr-2 h-4 w-4" />
                {t("preview")}
              </Button>
            </div>
          </CardContent>
        </Card>

        {/* Card 3: Recall Report */}
        <Card>
          <CardHeader className="pb-3">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <AlertTriangle className="h-5 w-5 text-destructive" />
                <CardTitle className="text-lg">{t("recall")}</CardTitle>
              </div>
              <Badge
                variant="outline"
                className="border-green-500 text-green-700 dark:text-green-400 text-xs"
              >
                {t("complianceBadge")}
              </Badge>
            </div>
          </CardHeader>
          <CardContent className="space-y-4">
            <p className="text-sm text-muted-foreground">{t("recallDesc")}</p>

            {/* Date range */}
            <div className="grid grid-cols-2 gap-2">
              <div className="space-y-1.5">
                <label className="text-sm font-medium">{t("dateFrom")}</label>
                <input
                  type="date"
                  value={dateFrom}
                  onChange={(e) => setDateFrom(e.target.value)}
                  className="border-input bg-background ring-offset-background focus:ring-ring flex h-9 w-full rounded-md border px-3 py-1 text-sm shadow-sm transition-colors focus:ring-1 focus:outline-none"
                />
              </div>
              <div className="space-y-1.5">
                <label className="text-sm font-medium">{t("dateTo")}</label>
                <input
                  type="date"
                  value={dateTo}
                  onChange={(e) => setDateTo(e.target.value)}
                  className="border-input bg-background ring-offset-background focus:ring-ring flex h-9 w-full rounded-md border px-3 py-1 text-sm shadow-sm transition-colors focus:ring-1 focus:outline-none"
                />
              </div>
            </div>

            {/* Compliance note */}
            <p className="text-xs text-muted-foreground italic">
              {t("complianceNote")}
            </p>

            {/* Action buttons */}
            <div className="flex flex-col gap-2">
              <Button
                variant="default"
                size="sm"
                className="w-full justify-start"
                onClick={() => handleDownload("recall", "pdf")}
              >
                <Download className="mr-2 h-4 w-4" />
                {t("downloadPdf")}
              </Button>
              <Button
                variant="outline"
                size="sm"
                className="w-full justify-start"
                onClick={() => handleDownload("recall", "csv")}
              >
                <FileText className="mr-2 h-4 w-4" />
                {t("downloadCsv")}
              </Button>
              <Button
                variant="ghost"
                size="sm"
                className="w-full justify-start"
                onClick={() => handlePreview("recall")}
              >
                <Eye className="mr-2 h-4 w-4" />
                {t("preview")}
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Preview Sheet */}
      <Sheet open={previewOpen} onOpenChange={setPreviewOpen}>
        <SheetContent
          side="right"
          className="w-full sm:max-w-lg overflow-y-auto"
        >
          <SheetHeader>
            <SheetTitle>{t("previewTitle")}</SheetTitle>
            <SheetDescription>
              {previewType === "monthly" && t("monthly")}
              {previewType === "memberList" && t("memberList")}
              {previewType === "recall" && t("recall")}
            </SheetDescription>
          </SheetHeader>

          <div className="mt-6">
            {previewType === "monthly" && (
              <MonthlyPreview t={t} query={monthlyQuery} />
            )}
            {previewType === "memberList" && (
              <MemberListPreview t={t} query={memberListQuery} />
            )}
            {previewType === "recall" && (
              <RecallPreview t={t} query={recallQuery} />
            )}
          </div>

          <SheetFooter className="mt-6">
            <SheetClose asChild>
              <Button variant="outline">{t("close")}</Button>
            </SheetClose>
          </SheetFooter>
        </SheetContent>
      </Sheet>
    </div>
  )
}

/* ─── Preview Components ─── */

function PreviewSkeleton() {
  return (
    <div className="space-y-4">
      <div className="grid grid-cols-2 gap-4">
        <Skeleton className="h-20 rounded-lg" />
        <Skeleton className="h-20 rounded-lg" />
        <Skeleton className="h-20 rounded-lg" />
        <Skeleton className="h-20 rounded-lg" />
      </div>
      <Skeleton className="h-6 w-32" />
      <Skeleton className="h-40 rounded-lg" />
    </div>
  )
}

function MonthlyPreview({
  t,
  query,
}: {
  t: ReturnType<typeof useTranslations<"reports">>
  query: ReturnType<typeof useMonthlyReportQuery>
}) {
  if (query.isLoading) return <PreviewSkeleton />

  // Fallback to mock data if backend unavailable
  const apiData = query.data
  const data = apiData
    ? {
        totalDistributions: apiData.totalDistributions,
        totalGrams: apiData.totalGrams,
        uniqueMembers: apiData.uniqueMembers,
        averagePerMember: apiData.averagePerDistribution,
        topStrains: apiData.topStrains.map((s) => ({
          name: s.name,
          grams: s.grams,
          percent: Math.round((s.grams / apiData.totalGrams) * 1000) / 10,
        })),
      }
    : mockMonthlyReportPreview

  return (
    <div className="space-y-6">
      {/* Summary stats */}
      <div className="grid grid-cols-2 gap-4">
        <StatCard
          label={t("totalDistributions")}
          value={String(data.totalDistributions)}
        />
        <StatCard label={t("totalGrams")} value={`${data.totalGrams}g`} />
        <StatCard
          label={t("uniqueMembers")}
          value={String(data.uniqueMembers)}
        />
        <StatCard
          label={t("averagePerMember")}
          value={`${data.averagePerMember}g`}
        />
      </div>

      {/* Top strains table */}
      <div>
        <h4 className="text-sm font-semibold mb-2">{t("topStrains")}</h4>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>{t("strain")}</TableHead>
              <TableHead className="text-right">{t("grams")}</TableHead>
              <TableHead className="text-right">{t("percent")}</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {data.topStrains.map((strain) => (
              <TableRow key={strain.name}>
                <TableCell className="font-medium">{strain.name}</TableCell>
                <TableCell className="text-right">{strain.grams}g</TableCell>
                <TableCell className="text-right">{strain.percent}%</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
    </div>
  )
}

function MemberListPreview({
  t,
  query,
}: {
  t: ReturnType<typeof useTranslations<"reports">>
  query: ReturnType<typeof useMemberListReportQuery>
}) {
  if (query.isLoading) return <PreviewSkeleton />

  // Fallback to mock data if backend unavailable
  const apiData = query.data
  const data = apiData
    ? {
        totalMembers: apiData.totalMembers,
        active: apiData.activeMembers,
        suspended: apiData.suspendedMembers,
        expelled: apiData.expelledMembers,
        members: apiData.members.map((m) => ({
          memberNumber: m.id.slice(0, 5),
          name: m.name,
          status: m.status as "ACTIVE" | "SUSPENDED" | "EXPELLED",
          monthlyUsage: 0,
          monthlyLimit: 50,
        })),
      }
    : mockMemberListPreview

  const statusBadge = (status: string) => {
    switch (status) {
      case "ACTIVE":
        return <Badge variant="default">Aktiv</Badge>
      case "SUSPENDED":
        return <Badge variant="secondary">Gesperrt</Badge>
      case "EXPELLED":
        return <Badge variant="destructive">Ausgeschlossen</Badge>
      default:
        return null
    }
  }

  return (
    <div className="space-y-4">
      {/* Summary */}
      <div className="grid grid-cols-3 gap-2">
        <StatCard label={t("allStatuses")} value={String(data.totalMembers)} />
        <StatCard label={t("activeOnly")} value={String(data.active)} />
        <StatCard label={t("suspendedOnly")} value={String(data.suspended)} />
      </div>

      {/* Members table */}
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>{t("memberNumber")}</TableHead>
            <TableHead>{t("name")}</TableHead>
            <TableHead>{t("status")}</TableHead>
            <TableHead className="text-right">{t("usage")}</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {data.members.map((member) => (
            <TableRow key={member.memberNumber}>
              <TableCell className="font-mono text-xs">
                {member.memberNumber}
              </TableCell>
              <TableCell className="font-medium">{member.name}</TableCell>
              <TableCell>{statusBadge(member.status)}</TableCell>
              <TableCell className="text-right">
                {member.monthlyUsage}/{member.monthlyLimit}g
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  )
}

function RecallPreview({
  t,
  query,
}: {
  t: ReturnType<typeof useTranslations<"reports">>
  query: ReturnType<typeof useRecallReportQuery>
}) {
  if (query.isLoading) return <PreviewSkeleton />

  // Fallback to mock data if backend unavailable
  const apiData = query.data
  const data = apiData
    ? {
        recalledBatches: apiData.totalRecalls,
        affectedDistributions: apiData.batches.reduce(
          (acc, b) => acc + Math.ceil(b.gramsAffected / 5),
          0
        ),
        affectedMembers: apiData.batches.length * 3,
        batches: apiData.batches.map((b) => ({
          batchId: b.id,
          strain: b.strainName,
          recalledAt: b.recalledAt,
          reason: b.reason,
          originalGrams: b.gramsAffected * 3,
          distributedGrams: b.gramsAffected,
          affectedMembers: 3,
          affectedDistributions: Math.ceil(b.gramsAffected / 5),
        })),
      }
    : mockRecallReportPreview

  return (
    <div className="space-y-6">
      {/* Summary stats */}
      <div className="grid grid-cols-3 gap-2">
        <StatCard
          label={t("recalledBatches")}
          value={String(data.recalledBatches)}
        />
        <StatCard
          label={t("affectedDistributions")}
          value={String(data.affectedDistributions)}
        />
        <StatCard
          label={t("affectedMembers")}
          value={String(data.affectedMembers)}
        />
      </div>

      {/* Batches detail */}
      {data.batches.map((batch) => (
        <Card key={batch.batchId}>
          <CardContent className="pt-4 space-y-2">
            <div className="flex items-center justify-between">
              <span className="font-mono text-sm font-semibold">
                {batch.batchId}
              </span>
              <Badge variant="destructive">{batch.strain}</Badge>
            </div>
            <div className="grid grid-cols-2 gap-x-4 gap-y-1 text-sm">
              <span className="text-muted-foreground">{t("recalledAt")}:</span>
              <span>{batch.recalledAt}</span>
              <span className="text-muted-foreground">{t("reason")}:</span>
              <span>{batch.reason}</span>
              <span className="text-muted-foreground">{t("original")}:</span>
              <span>{batch.originalGrams}g</span>
              <span className="text-muted-foreground">{t("distributed")}:</span>
              <span>{batch.distributedGrams}g</span>
              <span className="text-muted-foreground">
                {t("affectedMembers")}:
              </span>
              <span>{batch.affectedMembers}</span>
              <span className="text-muted-foreground">
                {t("affectedDistributions")}:
              </span>
              <span>{batch.affectedDistributions}</span>
            </div>
          </CardContent>
        </Card>
      ))}
    </div>
  )
}

/* ─── Shared Components ─── */

function StatCard({ label, value }: { label: string; value: string }) {
  return (
    <div className="bg-muted/50 rounded-lg p-3 text-center">
      <p className="text-lg font-bold">{value}</p>
      <p className="text-xs text-muted-foreground">{label}</p>
    </div>
  )
}
