"use client"

import { useLocale, useTranslations } from "next-intl"
import {
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  Legend,
  Pie,
  PieChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Field, FieldLabel } from "@/components/ui/field"
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Skeleton } from "@/components/ui/skeleton"
import type { ChartSlice, TopCompanyRow } from "@/lib/api/dashboard"
import { chartColor } from "@/lib/chart-colors"

export const TOP_COMPANIES_LIMIT_OPTIONS = [5, 10, 15, 20, 25, 50] as const

function formatOrdersTotal(value: number, locale: string) {
  return new Intl.NumberFormat(locale, {
    maximumFractionDigits: 2,
  }).format(value)
}

type TopCompaniesTooltipProps = {
  active?: boolean
  payload?: ReadonlyArray<{ value?: number | string }>
  label?: string | number
  ordersTotalLabel: string
  locale: string
}

function TopCompaniesTooltip({
  active,
  payload,
  label,
  ordersTotalLabel,
  locale,
}: TopCompaniesTooltipProps) {
  if (!active || !payload?.length) return null

  const rawTotal = payload[0]?.value
  const total = typeof rawTotal === "number" ? rawTotal : Number(rawTotal)
  if (!Number.isFinite(total)) return null

  return (
    <div className="bg-popover shadow-md px-3 py-2 border rounded-md text-popover-foreground">
      <p className="max-w-48 font-medium text-xs leading-snug">{label}</p>
      <p className="mt-1 text-muted-foreground text-xs">{ordersTotalLabel}</p>
      <p className="font-semibold tabular-nums text-sm">
        {formatOrdersTotal(total, locale)}
      </p>
    </div>
  )
}

export function SuperDashboardCharts({
  topCompanies,
  topCompaniesLimit,
  onTopCompaniesLimitChange,
  isTopCompaniesLoading = false,
  isTopCompaniesError = false,
  plans,
  themes,
}: {
  topCompanies: TopCompanyRow[]
  topCompaniesLimit: number
  onTopCompaniesLimitChange: (limit: number) => void
  isTopCompaniesLoading?: boolean
  isTopCompaniesError?: boolean
  plans: ChartSlice[]
  themes: ChartSlice[]
}) {
  const t = useTranslations("Dashboard.charts")
  const tc = useTranslations("Common")
  const locale = useLocale()

  const grandTotalData = topCompanies.map((company) => ({
    company: company.name,
    total: company.total,
  }))

  return (
    <div className="gap-4 grid md:grid-cols-2 px-4 lg:px-6">
      <Card>
        <CardHeader>
          <CardTitle className="font-medium text-sm">{t("subscriptionPlans")}</CardTitle>
        </CardHeader>
        <CardContent className="h-72">
          <ResponsiveContainer width="100%" height="100%">
            <PieChart>
              <Tooltip />
              <Legend />
              <Pie data={plans} dataKey="value" nameKey="name" outerRadius={90}>
                {plans.map((_, index) => (
                  <Cell key={index} fill={chartColor(index)} />
                ))}
              </Pie>
            </PieChart>
          </ResponsiveContainer>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="font-medium text-sm">{t("themes")}</CardTitle>
        </CardHeader>
        <CardContent className="h-72">
          <ResponsiveContainer width="100%" height="100%">
            <BarChart data={themes} margin={{ top: 8, right: 12, left: 4, bottom: 72 }}>
              <CartesianGrid vertical={false} strokeDasharray="3 3" />
              <XAxis
                dataKey="name"
                tickLine={false}
                axisLine={false}
                interval={0}
                angle={-20}
                textAnchor="end"
                height={15}
                tickMargin={8}
                tick={{ fontSize: 11 }}
              />
              <YAxis tickLine={false} axisLine={false} width={56} />
              <Tooltip />
              {/* <Legend /> */}
              <Bar dataKey="value" radius={[6, 6, 0, 0]}>
                {themes.map((_, index) => (
                  <Cell key={index} fill={chartColor(index, 2)} />
                ))}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </CardContent>
      </Card>

      <Card className="md:col-span-2">
        <CardHeader className="flex sm:flex-row flex-col sm:justify-between sm:items-center gap-3 space-y-0">
          <CardTitle className="font-medium text-sm">{t("topCompanies")}</CardTitle>
          <Field orientation="horizontal" className="w-fit">
            <FieldLabel htmlFor="top-companies-limit">{t("topCompaniesLimit")}</FieldLabel>
            <Select
              value={String(topCompaniesLimit)}
              disabled={isTopCompaniesLoading}
              onValueChange={(value) => onTopCompaniesLimitChange(Number(value))}
            >
              <SelectTrigger className="w-20" id="top-companies-limit">
                <SelectValue />
              </SelectTrigger>
              <SelectContent align="end">
                <SelectGroup>
                  {TOP_COMPANIES_LIMIT_OPTIONS.map((option) => (
                    <SelectItem key={option} value={String(option)}>
                      {option}
                    </SelectItem>
                  ))}
                </SelectGroup>
              </SelectContent>
            </Select>
          </Field>
        </CardHeader>
        <CardContent className="relative min-h-96 h-96">
          {isTopCompaniesLoading ? (
            <Skeleton className="w-full h-full" />
          ) : isTopCompaniesError ? (
            <div className="flex justify-center items-center h-full text-destructive text-sm">
              {tc("api.errorTitle")}
            </div>
          ) : grandTotalData.length === 0 ? (
            <div className="flex justify-center items-center h-full text-muted-foreground text-sm">
              {tc("table.noResults")}
            </div>
          ) : (
          <ResponsiveContainer width="100%" height="100%">
            <BarChart
              data={grandTotalData}
              margin={{ top: 16, right: 12, left: 4, bottom: 72 }}
            >
              <CartesianGrid vertical={false} strokeDasharray="3 3" />
              <XAxis
                dataKey="company"
                tickLine={false}
                axisLine={false}
                interval={0}
                angle={-20}
                textAnchor="end"
                height={15}
                tickMargin={8}
                tick={{ fontSize: 11 }}
              />
              <YAxis tickLine={false} axisLine={false} width={56} />
              <Tooltip
                cursor={{ fill: "var(--muted)", opacity: 0.35 }}
                offset={16}
                wrapperStyle={{ outline: "none", zIndex: 20 }}
                content={({ active, payload, label }) => (
                  <TopCompaniesTooltip
                    active={active}
                    payload={Array.isArray(payload) ? payload.map((p) => ({ value: p.value as number | string })) : []}
                    label={label}
                    ordersTotalLabel={t("ordersTotal")}
                    locale={locale}
                  />
                )}
              />
              <Bar dataKey="total" radius={[6, 6, 0, 0]}>
                {grandTotalData.map((_, index) => (
                  <Cell key={index} fill={chartColor(index)} />
                ))}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
