"use client";

import { useState } from "react";
import {
  Loader2,
  Database,
  RefreshCw,
  Sparkles,
  BarChart3,
} from "lucide-react";
import { Button } from "@/shared/components/ui/button";
import { Badge } from "@/shared/components/ui/badge";
import { Card, CardContent } from "@/shared/components/ui/card";
import { cn } from "@/shared/lib/utils";
import type { DbSummary } from "../parcel-sync-types";
import { relativeTime } from "../parcel-sync-types";
import {
  LAYER_CATEGORY_LABELS,
  type LayerCategory,
  findLayerById,
} from "../../services/eterra-layers";
import { UatDashboard } from "../uat-dashboard";

/* ------------------------------------------------------------------ */
/*  Props                                                              */
/* ------------------------------------------------------------------ */

type DatabaseTabProps = {
  siruta: string;
  sirutaValid: boolean;
  dbSummary: DbSummary | null;
  dbSummaryLoading: boolean;
  onRefresh: () => void;
};

/* ------------------------------------------------------------------ */
/*  Component                                                          */
/* ------------------------------------------------------------------ */

export function DatabaseTab({
  siruta,
  sirutaValid,
  dbSummary,
  dbSummaryLoading,
  onRefresh,
}: DatabaseTabProps) {
  const [dashboardSiruta, setDashboardSiruta] = useState<string | null>(null);

  /* ── Loading state ──────────────────────────────────────────────── */
  if (dbSummaryLoading && !dbSummary) {
    return (
      <Card>
        <CardContent className="py-12 text-center text-muted-foreground">
          <Loader2 className="h-8 w-8 mx-auto mb-3 animate-spin opacity-40" />
          <p>Se încarcă datele din baza de date…</p>
        </CardContent>
      </Card>
    );
  }

  /* ── Empty state ────────────────────────────────────────────────── */
  if (!dbSummary || dbSummary.totalFeatures === 0) {
    return (
      <Card>
        <CardContent className="py-12 text-center text-muted-foreground">
          <Database className="h-10 w-10 mx-auto mb-3 opacity-30" />
          <p className="font-medium">Nicio dată în baza de date</p>
          <p className="text-xs mt-1">
            Folosește tab-ul Export pentru a sincroniza date din eTerra.
          </p>
        </CardContent>
      </Card>
    );
  }

  /* ── Populated state ────────────────────────────────────────────── */
  return (
    <>
      {/* Header row */}
      <div className="flex items-center justify-between gap-3">
        <div className="flex items-center gap-2">
          <Database className="h-4 w-4 text-muted-foreground" />
          <span className="text-sm font-medium">
            {dbSummary.totalFeatures.toLocaleString("ro-RO")} entități
          </span>
          <span className="text-xs text-muted-foreground">
            din {dbSummary.totalUats} UAT-uri
          </span>
        </div>
        <Button
          variant="ghost"
          size="sm"
          className="h-7 text-xs"
          disabled={dbSummaryLoading}
          onClick={onRefresh}
        >
          {dbSummaryLoading ? (
            <Loader2 className="h-3 w-3 mr-1 animate-spin" />
          ) : (
            <RefreshCw className="h-3 w-3 mr-1" />
          )}
          Reîncarcă
        </Button>
      </div>

      {/* UAT cards */}
      {dbSummary.uats.map((uat) => {
        const catCounts: Record<string, number> = {};
        let enrichedTotal = 0;
        let noGeomTotal = 0;
        let oldestSync: Date | null = null;
        for (const layer of uat.layers) {
          const cat =
            findLayerById(layer.layerId)?.category ?? "administrativ";
          catCounts[cat] = (catCounts[cat] ?? 0) + layer.count;
          enrichedTotal += layer.enrichedCount;
          noGeomTotal += layer.noGeomCount ?? 0;
          if (layer.lastSynced) {
            const d = new Date(layer.lastSynced);
            if (!oldestSync || d < oldestSync) oldestSync = d;
          }
        }
        const isCurrentUat = sirutaValid && uat.siruta === siruta;

        return (
          <div key={uat.siruta} className="space-y-3">
            <Card
              className={cn(
                "transition-colors",
                isCurrentUat && "ring-1 ring-emerald-400/50",
              )}
            >
              <CardContent className="py-3 px-4 space-y-2">
                {/* UAT header row */}
                <div className="flex items-center gap-2 flex-wrap">
                  <span className="text-sm font-semibold">
                    {uat.uatName}
                  </span>
                  {uat.county && (
                    <span className="text-[10px] text-muted-foreground">
                      ({uat.county})
                    </span>
                  )}
                  <span className="text-[10px] font-mono text-muted-foreground">
                    #{uat.siruta}
                  </span>
                  {isCurrentUat && (
                    <Badge
                      variant="outline"
                      className="text-[9px] h-4 text-emerald-600 border-emerald-300 dark:text-emerald-400 dark:border-emerald-700"
                    >
                      selectat
                    </Badge>
                  )}
                  <span className="ml-auto flex items-center gap-2">
                    <Button
                      variant="ghost"
                      size="sm"
                      className="h-5 px-2 text-[10px] gap-1 text-indigo-600 dark:text-indigo-400 hover:text-indigo-700 hover:bg-indigo-50 dark:hover:bg-indigo-950"
                      onClick={() =>
                        setDashboardSiruta(
                          dashboardSiruta === uat.siruta
                            ? null
                            : uat.siruta,
                        )
                      }
                    >
                      <BarChart3 className="h-3 w-3" />
                      Dashboard
                    </Button>
                    <span className="text-xs text-muted-foreground">
                      {oldestSync ? relativeTime(oldestSync) : "—"}
                    </span>
                  </span>
                </div>

                {/* Category counts in a single compact row */}
                <div className="flex items-center gap-2 flex-wrap text-xs">
                  {(
                    Object.entries(LAYER_CATEGORY_LABELS) as [
                      LayerCategory,
                      string,
                    ][]
                  ).map(([cat, label]) => {
                    const count = catCounts[cat] ?? 0;
                    if (count === 0) return null;
                    return (
                      <span
                        key={cat}
                        className="inline-flex items-center gap-1"
                      >
                        <span className="text-muted-foreground">
                          {label}:
                        </span>
                        <span className="font-medium tabular-nums">
                          {count.toLocaleString("ro-RO")}
                        </span>
                      </span>
                    );
                  })}
                  {enrichedTotal > 0 && (
                    <span className="inline-flex items-center gap-1">
                      <Sparkles className="h-3 w-3 text-teal-600 dark:text-teal-400" />
                      <span className="text-muted-foreground">
                        Magic:
                      </span>
                      <span className="font-medium tabular-nums text-teal-700 dark:text-teal-400">
                        {enrichedTotal.toLocaleString("ro-RO")}
                      </span>
                    </span>
                  )}
                  {noGeomTotal > 0 && (
                    <span className="inline-flex items-center gap-1">
                      <span className="text-muted-foreground">
                        Fără geom:
                      </span>
                      <span className="font-medium tabular-nums text-amber-600 dark:text-amber-400">
                        {noGeomTotal.toLocaleString("ro-RO")}
                      </span>
                    </span>
                  )}
                </div>

                {/* Layer detail pills */}
                <div className="flex gap-1.5 flex-wrap">
                  {uat.layers
                    .sort((a, b) => b.count - a.count)
                    .map((layer) => {
                      const meta = findLayerById(layer.layerId);
                      const label =
                        meta?.label ?? layer.layerId.replace(/_/g, " ");
                      const isEnriched = layer.enrichedCount > 0;
                      return (
                        <span
                          key={layer.layerId}
                          className={cn(
                            "inline-flex items-center gap-1 rounded-md border px-1.5 py-0.5 text-[10px]",
                            isEnriched
                              ? "border-teal-200 bg-teal-50/50 dark:border-teal-800 dark:bg-teal-950/30"
                              : "border-muted bg-muted/30",
                          )}
                          title={`${label}: ${layer.count} entități${isEnriched ? `, ${layer.enrichedCount} îmbogățite` : ""}${layer.lastSynced ? `, sync: ${new Date(layer.lastSynced).toLocaleDateString("ro-RO")}` : ""}`}
                        >
                          <span className="truncate max-w-[120px]">
                            {label}
                          </span>
                          <span className="font-medium tabular-nums">
                            {layer.count.toLocaleString("ro-RO")}
                          </span>
                          {isEnriched && (
                            <Sparkles className="h-2.5 w-2.5 text-teal-600 dark:text-teal-400" />
                          )}
                        </span>
                      );
                    })}
                </div>
              </CardContent>
            </Card>

            {/* Dashboard panel (expanded below card) */}
            {dashboardSiruta === uat.siruta && (
              <UatDashboard
                siruta={uat.siruta}
                uatName={uat.uatName}
                onClose={() => setDashboardSiruta(null)}
              />
            )}
          </div>
        );
      })}
    </>
  );
}
