"use client";

import { useState, useMemo } from "react";
import {
  Line, LineChart, CartesianGrid, XAxis, YAxis, Pie, PieChart, Cell,
} from "recharts";

import {
  Card, CardContent, CardDescription, CardHeader, CardTitle,
} from "@/components/ui/card";
import {
  ChartContainer, ChartTooltip, type ChartConfig,
} from "@/components/ui/chart";

type View = "trend" | "dagilim";

const PIE_COLORS = [
  "hsl(221, 83%, 53%)",
  "hsl(142, 71%, 45%)",
  "hsl(38, 92%, 50%)",
  "hsl(280, 68%, 58%)",
  "hsl(10, 80%, 55%)",
  "hsl(200, 65%, 50%)",
];

const chartConfig = {
  ilanSayisi:     { label: "İlan",     color: "hsl(221, 83%, 53%)" },
  musteriSayisi:  { label: "Müşteri",  color: "hsl(142, 71%, 45%)" },
  aktiviteSayisi: { label: "Aktivite", color: "hsl(38, 92%, 50%)"  },
} satisfies ChartConfig;

const SERIES = [
  { dataKey: "ilanSayisi",     label: "İlan",     color: "hsl(221, 83%, 53%)" },
  { dataKey: "musteriSayisi",  label: "Müşteri",  color: "hsl(142, 71%, 45%)" },
  { dataKey: "aktiviteSayisi", label: "Aktivite", color: "hsl(38, 92%, 50%)"  },
] as const;

export function ChartAreaInteractive({
  ilanTrend, musteriTrend, aktiviteTrend, portfoyDagilim,
}: {
  ilanTrend: { ay: string; ilanSayisi: number }[];
  musteriTrend: { ay: string; musteriSayisi: number }[];
  aktiviteTrend: { ay: string; aktiviteSayisi: number }[];
  portfoyDagilim: { tip: string; label: string; sayi: number }[];
}) {
  const [view, setView] = useState<View>("trend");

  const trendData = useMemo(() =>
    ilanTrend.map((item, i) => ({
      ay: item.ay,
      ilanSayisi: item.ilanSayisi,
      musteriSayisi: musteriTrend[i]?.musteriSayisi ?? 0,
      aktiviteSayisi: aktiviteTrend[i]?.aktiviteSayisi ?? 0,
    })),
    [ilanTrend, musteriTrend, aktiviteTrend]
  );

  const dagilimTotal = portfoyDagilim.reduce((s, d) => s + d.sayi, 0);

  return (
    /*
     * Mobil: kart doğal yüksekliğinde (overflow: hidden her iki eksen).
     * Desktop: lg:h-full ile grid item'ı tamamen doldurur (items-stretch ile eşit yükseklik).
     */
    <Card className="overflow-hidden flex flex-col lg:h-full">
      <CardHeader className="pb-2 shrink-0">
        <div className="flex items-start justify-between gap-3 flex-wrap">
          <div>
            <CardTitle>Portföy Analitiği</CardTitle>
            <CardDescription>
              {view === "trend"
                ? "Son 6 ay — ilan, müşteri ve aktivite"
                : "Aktif portföy dağılımı"}
            </CardDescription>
          </div>
          <div className="flex rounded-lg border text-xs overflow-hidden shrink-0">
            {(["trend", "dagilim"] as View[]).map((v, i) => (
              <button
                key={v}
                onClick={() => setView(v)}
                className={`px-3 py-1.5 font-medium transition-colors ${i > 0 ? "border-l" : ""} ${
                  view === v
                    ? "bg-primary text-primary-foreground"
                    : "hover:bg-muted text-muted-foreground"
                }`}
              >
                {v === "trend" ? "Trend" : "Dağılım"}
              </button>
            ))}
          </div>
        </div>
        {view === "trend" && (
          <div className="flex gap-3 mt-1">
            {SERIES.map((s) => (
              <span key={s.dataKey} className="flex items-center gap-1.5 text-xs text-muted-foreground">
                <span className="inline-block size-2 rounded-full shrink-0" style={{ backgroundColor: s.color }} />
                {s.label}
              </span>
            ))}
          </div>
        )}
      </CardHeader>

      {/*
       * CardContent:
       * - Mobil: padding normal, yükseklik = içerik (chart 180px sabit).
       * - Desktop: lg:flex-1 lg:min-h-0 ile kalan alanı doldurur.
       *   min-h-0 zorunlu: flex-1 tek başına overflow'u engellemez.
       */}
      <CardContent className="px-2 sm:px-4 pb-4 lg:flex-1 lg:min-h-0">
        {view === "trend" ? (
          /*
           * h-[180px]: mobilde sabit yükseklik → Recharts collapse etmez.
           * lg:h-full: desktop'ta CardContent'in tamamını doldurur.
           */
          <ChartContainer config={chartConfig} className="h-[180px] lg:h-full w-full">
            <LineChart data={trendData} margin={{ top: 8, right: 8, left: -20, bottom: 0 }}>
              <CartesianGrid vertical={false} strokeDasharray="3 3" />
              <XAxis
                dataKey="ay"
                tickLine={false}
                axisLine={false}
                tickMargin={8}
                tick={{ fontSize: 11 }}
              />
              <YAxis
                tickLine={false}
                axisLine={false}
                allowDecimals={false}
                tick={{ fontSize: 11 }}
              />
              <ChartTooltip
                content={({ active, payload, label }) => {
                  if (!active || !payload?.length) return null;
                  return (
                    <div className="rounded-lg border bg-background px-3 py-2 text-sm shadow-md space-y-1">
                      <p className="font-medium text-xs text-muted-foreground mb-1.5">{label}</p>
                      {payload.map((p) => {
                        const s = SERIES.find((x) => x.dataKey === p.dataKey);
                        return (
                          <div key={p.dataKey} className="flex items-center gap-2">
                            <span className="size-2 rounded-full shrink-0" style={{ backgroundColor: s?.color }} />
                            <span className="flex-1">{s?.label}</span>
                            <span className="font-semibold tabular-nums">{p.value}</span>
                          </div>
                        );
                      })}
                    </div>
                  );
                }}
              />
              {SERIES.map((s) => (
                <Line
                  key={s.dataKey}
                  type="monotone"
                  dataKey={s.dataKey}
                  stroke={s.color}
                  strokeWidth={2}
                  dot={{ r: 3, fill: s.color, strokeWidth: 0 }}
                  activeDot={{ r: 5, fill: s.color, strokeWidth: 0 }}
                />
              ))}
            </LineChart>
          </ChartContainer>
        ) : (
          <div className="flex flex-col sm:flex-row gap-6 items-center h-[180px] lg:h-full">
            {portfoyDagilim.length === 0 ? (
              <p className="text-sm text-muted-foreground w-full text-center py-8">
                Henüz aktif ilan yok
              </p>
            ) : (
              <>
                <div className="shrink-0">
                  <PieChart width={150} height={150}>
                    <Pie
                      data={portfoyDagilim}
                      dataKey="sayi"
                      nameKey="label"
                      cx={75} cy={75}
                      innerRadius={46}
                      outerRadius={68}
                      paddingAngle={2}
                      strokeWidth={0}
                    >
                      {portfoyDagilim.map((_, i) => (
                        <Cell key={i} fill={PIE_COLORS[i % PIE_COLORS.length]} />
                      ))}
                    </Pie>
                    <ChartTooltip
                      content={({ active, payload }) => {
                        if (!active || !payload?.[0]) return null;
                        const d = payload[0].payload as { label: string; sayi: number };
                        const pct = dagilimTotal > 0 ? Math.round((d.sayi / dagilimTotal) * 100) : 0;
                        return (
                          <div className="rounded-lg border bg-background px-3 py-2 text-sm shadow-sm">
                            <p className="font-medium">{d.label}</p>
                            <p className="text-muted-foreground">{d.sayi} ilan · %{pct}</p>
                          </div>
                        );
                      }}
                    />
                  </PieChart>
                </div>
                <div className="flex-1 min-w-0 w-full space-y-2.5 overflow-y-auto">
                  {portfoyDagilim.map((d, i) => {
                    const pct = dagilimTotal > 0 ? Math.round((d.sayi / dagilimTotal) * 100) : 0;
                    return (
                      <div key={d.tip}>
                        <div className="flex items-center gap-2 mb-1">
                          <span className="size-2.5 rounded-full shrink-0" style={{ backgroundColor: PIE_COLORS[i % PIE_COLORS.length] }} />
                          <span className="text-sm flex-1 min-w-0 truncate">{d.label}</span>
                          <span className="text-sm font-semibold tabular-nums">{d.sayi}</span>
                          <span className="text-xs text-muted-foreground w-8 text-right">%{pct}</span>
                        </div>
                        <div className="ml-4 h-1 rounded-full bg-muted overflow-hidden">
                          <div
                            className="h-full rounded-full transition-all"
                            style={{ width: `${pct}%`, backgroundColor: PIE_COLORS[i % PIE_COLORS.length] }}
                          />
                        </div>
                      </div>
                    );
                  })}
                </div>
              </>
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
}
