"use client"

import { use } from "react"
import Link from "next/link"
import { useGrowEntryQuery } from "@/services/grow"
import { format } from "date-fns"
import { de } from "date-fns/locale"
import { useTranslations } from "next-intl"
import {
  CartesianGrid,
  Line,
  LineChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts"
import { ArrowLeft, Camera, Droplets, Thermometer } from "lucide-react"

import type { GrowStage } from "@/services/grow"

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"

const STAGE_COLORS: Record<GrowStage, string> = {
  SEEDLING: "bg-lime-500/20 text-lime-700 dark:text-lime-400",
  VEGETATIVE: "bg-green-500/20 text-green-700 dark:text-green-400",
  FLOWERING: "bg-purple-500/20 text-purple-700 dark:text-purple-400",
  HARVEST: "bg-amber-500/20 text-amber-700 dark:text-amber-400",
  DRYING: "bg-orange-500/20 text-orange-700 dark:text-orange-400",
  CURING: "bg-yellow-500/20 text-yellow-700 dark:text-yellow-400",
  COMPLETE: "bg-emerald-500/20 text-emerald-700 dark:text-emerald-400",
}

export default function GrowDetailPage({
  params,
}: {
  params: Promise<{ id: string }>
}) {
  const { id } = use(params)
  const t = useTranslations("grow")
  const { data: entry, isLoading } = useGrowEntryQuery(id)

  if (isLoading || !entry) {
    return (
      <div className="space-y-6">
        <ChartSkeleton />
        <TableSkeleton />
      </div>
    )
  }

  // Prepare sensor chart data (temp + humidity over time)
  const sensorChartData = entry.sensors
    .filter(
      (s) => s.readingType === "TEMPERATURE" || s.readingType === "HUMIDITY"
    )
    .reduce(
      (acc, s) => {
        const date = format(new Date(s.recordedAt), "dd.MM", { locale: de })
        const existing = acc.find((d) => d.date === date)
        if (existing) {
          if (s.readingType === "TEMPERATURE") existing.temp = s.value
          if (s.readingType === "HUMIDITY") existing.humidity = s.value
        } else {
          acc.push({
            date,
            temp: s.readingType === "TEMPERATURE" ? s.value : undefined,
            humidity: s.readingType === "HUMIDITY" ? s.value : undefined,
          })
        }
        return acc
      },
      [] as { date: string; temp?: number; humidity?: number }[]
    )
    .reverse()

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="icon" asChild>
          <Link href="/grow">
            <ArrowLeft className="h-4 w-4" />
          </Link>
        </Button>
        <div className="flex-1">
          <h1 className="text-2xl font-bold">{entry.name}</h1>
          <p className="text-sm text-muted-foreground">
            {t("startedAt")}:{" "}
            {format(new Date(entry.startedAt), "dd.MM.yyyy", { locale: de })}
          </p>
        </div>
        <Badge className={STAGE_COLORS[entry.status]} variant="secondary">
          {t(`stages.${entry.status}`)}
        </Badge>
      </div>

      {/* Timeline */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">{t("timeline")}</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="relative space-y-3">
            {entry.stages.map((stage, _i) => (
              <div key={stage.id} className="flex items-start gap-3">
                <div
                  className={`mt-1 h-3 w-3 rounded-full ${
                    stage.endedAt ? "bg-primary" : "bg-primary animate-pulse"
                  }`}
                />
                <div className="flex-1">
                  <div className="flex items-center gap-2">
                    <Badge
                      variant="secondary"
                      className={STAGE_COLORS[stage.stage]}
                    >
                      {t(`stages.${stage.stage}`)}
                    </Badge>
                    <span className="text-xs text-muted-foreground">
                      {format(new Date(stage.startedAt), "dd.MM.yyyy", {
                        locale: de,
                      })}
                      {stage.endedAt &&
                        ` — ${format(new Date(stage.endedAt), "dd.MM.yyyy", { locale: de })}`}
                    </span>
                  </div>
                  {stage.notes && (
                    <p className="mt-1 text-sm text-muted-foreground">
                      {stage.notes}
                    </p>
                  )}
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Sensor Chart */}
      {sensorChartData.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-base">
              <Thermometer className="h-4 w-4" />
              {t("sensors")}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={250}>
              <LineChart data={sensorChartData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="date" fontSize={12} />
                <YAxis yAxisId="temp" orientation="left" domain={[18, 30]} />
                <YAxis yAxisId="hum" orientation="right" domain={[40, 80]} />
                <Tooltip />
                <Line
                  yAxisId="temp"
                  type="monotone"
                  dataKey="temp"
                  stroke="#ef4444"
                  strokeWidth={2}
                  name={t("temperature")}
                  dot={false}
                />
                <Line
                  yAxisId="hum"
                  type="monotone"
                  dataKey="humidity"
                  stroke="#3b82f6"
                  strokeWidth={2}
                  name={t("humidity")}
                  dot={false}
                />
              </LineChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
      )}

      {/* Feeding Log */}
      {entry.feedings.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-base">
              <Droplets className="h-4 w-4" />
              {t("feeding")}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Datum</TableHead>
                  <TableHead>{t("nutrient")}</TableHead>
                  <TableHead>{t("amountMl")}</TableHead>
                  <TableHead>{t("waterLiters")}</TableHead>
                  <TableHead>{t("phAfter")}</TableHead>
                  <TableHead>{t("ecAfter")}</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {entry.feedings.map((f) => (
                  <TableRow key={f.id}>
                    <TableCell>
                      {format(new Date(f.fedAt), "dd.MM.yyyy", {
                        locale: de,
                      })}
                    </TableCell>
                    <TableCell>{f.nutrientName}</TableCell>
                    <TableCell>{f.amountMl} ml</TableCell>
                    <TableCell>
                      {f.waterLiters ? `${f.waterLiters} L` : "—"}
                    </TableCell>
                    <TableCell>{f.phAfter ?? "—"}</TableCell>
                    <TableCell>{f.ecAfter ?? "—"}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      {/* Photos */}
      {entry.photos.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-base">
              <Camera className="h-4 w-4" />
              {t("photos")} ({entry.photos.length})
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid gap-4 sm:grid-cols-2 md:grid-cols-3">
              {entry.photos.map((photo) => (
                <div
                  key={photo.id}
                  className="rounded-lg border bg-muted/50 p-4 text-center"
                >
                  <Camera className="mx-auto mb-2 h-8 w-8 text-muted-foreground" />
                  <p className="text-sm font-medium">
                    {photo.caption ?? "Foto"}
                  </p>
                  <p className="text-xs text-muted-foreground">
                    {format(new Date(photo.takenAt), "dd.MM.yyyy", {
                      locale: de,
                    })}
                  </p>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
