"use client";

import { useState, useMemo } from "react";
import type { GraftCombination, Plant, SoilProfile } from "@/types/api";

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

const VARIETY_COLORS = {
  scion: "bg-emerald-100 text-emerald-800",
  rootstock: "bg-blue-100 text-blue-800",
  both: "bg-violet-100 text-violet-800",
} as const;

const SOIL_TYPE_COLORS: Record<string, string> = {
  sandy: "bg-amber-100 text-amber-800",
  loam: "bg-lime-100 text-lime-800",
  clay: "bg-orange-100 text-orange-800",
  silt: "bg-cyan-100 text-cyan-800",
  peat: "bg-brown-100 text-stone-700 bg-stone-200",
  chalky: "bg-gray-100 text-gray-700",
};

function ToleranceBar({
  label,
  value,
  color = "bg-emerald-500",
}: {
  label: string;
  value: number;
  color?: string;
}) {
  return (
    <div className="flex items-center gap-2">
      <span className="w-16 shrink-0 text-xs text-stone-500">{label}</span>
      <div className="h-1.5 flex-1 rounded-full bg-stone-100">
        <div
          className={`h-1.5 rounded-full ${color}`}
          style={{ width: `${value * 10}%` }}
        />
      </div>
      <span className="w-4 text-right text-xs font-medium text-stone-600">
        {value}
      </span>
    </div>
  );
}

function Badge({ label, className }: { label: string; className?: string }) {
  return (
    <span
      className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium capitalize ${className}`}
    >
      {label}
    </span>
  );
}

// ---------------------------------------------------------------------------
// Plant Card
// ---------------------------------------------------------------------------

function PlantCard({ plant }: { plant: Plant }) {
  return (
    <div className="flex flex-col rounded-2xl border border-stone-200 bg-white p-4 shadow-sm transition hover:shadow-md hover:border-emerald-200 sm:p-5">
      <div className="mb-3 flex items-start justify-between gap-2">
        <div>
          <h3 className="text-sm font-semibold text-stone-900">{plant.name}</h3>
          <p className="text-xs italic text-stone-400">{plant.species}</p>
        </div>
        <Badge
          label={plant.variety_type}
          className={VARIETY_COLORS[plant.variety_type]}
        />
      </div>

      <div className="mb-4 space-y-1.5">
        <ToleranceBar label="Drought" value={plant.drought_tolerance} color="bg-amber-400" />
        <ToleranceBar label="Salinity" value={plant.salinity_tolerance} color="bg-blue-400" />
        <ToleranceBar label="Heat" value={plant.heat_tolerance} color="bg-red-400" />
        <ToleranceBar label="Cold" value={plant.cold_tolerance} color="bg-cyan-400" />
      </div>

      <div className="mt-auto grid grid-cols-2 gap-2 border-t border-stone-100 pt-3">
        <div>
          <p className="text-xs text-stone-400">pH Range</p>
          <p className="text-xs font-medium text-stone-700">
            {plant.optimal_ph_min}–{plant.optimal_ph_max}
          </p>
        </div>
        <div>
          <p className="text-xs text-stone-400">Growth Cycle</p>
          <p className="text-xs font-medium text-stone-700">
            {plant.growth_cycle_days} days
          </p>
        </div>
        <div>
          <p className="text-xs text-stone-400">Root Depth</p>
          <p className="text-xs font-medium capitalize text-stone-700">
            {plant.root_depth_category}
          </p>
        </div>
        <div>
          <p className="text-xs text-stone-400">Yield Potential</p>
          <p className="text-xs font-medium text-stone-700">
            {plant.yield_potential_kg_per_plant} kg/plant
          </p>
        </div>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Soil Card
// ---------------------------------------------------------------------------

function SoilCard({ soil }: { soil: SoilProfile }) {
  return (
    <div className="flex flex-col rounded-2xl border border-stone-200 bg-white p-4 shadow-sm transition hover:shadow-md hover:border-emerald-200 sm:p-5">
      <div className="mb-3">
        <h3 className="text-sm font-semibold text-stone-900">{soil.name}</h3>
        <div className="mt-1.5 flex flex-wrap gap-1.5">
          <Badge
            label={soil.soil_type}
            className={SOIL_TYPE_COLORS[soil.soil_type] ?? "bg-stone-100 text-stone-700"}
          />
          <Badge
            label={soil.climate_zone}
            className="bg-teal-100 text-teal-800"
          />
        </div>
      </div>

      <div className="mb-4 grid grid-cols-2 gap-3">
        <div className="rounded-xl bg-stone-50 px-3 py-2">
          <p className="text-xs text-stone-400">pH Level</p>
          <p className="text-sm font-semibold text-stone-800">{soil.ph_level}</p>
        </div>
        <div className="rounded-xl bg-stone-50 px-3 py-2">
          <p className="text-xs text-stone-400">Salinity</p>
          <p className="text-sm font-semibold text-stone-800">
            {soil.salinity_level} dS/m
          </p>
        </div>
        <div className="rounded-xl bg-stone-50 px-3 py-2">
          <p className="text-xs text-stone-400">Organic Matter</p>
          <p className="text-sm font-semibold text-stone-800">
            {soil.organic_matter_percent}%
          </p>
        </div>
        <div className="rounded-xl bg-stone-50 px-3 py-2">
          <p className="text-xs text-stone-400">Temperature</p>
          <p className="text-sm font-semibold text-stone-800">
            {soil.temperature_range_min}–{soil.temperature_range_max}°C
          </p>
        </div>
      </div>

      <div className="mt-auto grid grid-cols-2 gap-2 border-t border-stone-100 pt-3">
        <div>
          <p className="text-xs text-stone-400">Drainage</p>
          <p className="text-xs font-medium capitalize text-stone-700">
            {soil.drainage_rate}
          </p>
        </div>
        <div>
          <p className="text-xs text-stone-400">Water Retention</p>
          <p className="text-xs font-medium capitalize text-stone-700">
            {soil.water_retention}
          </p>
        </div>
        <div>
          <p className="text-xs text-stone-400">Native N / P / K</p>
          <p className="text-xs font-medium text-stone-700">
            {soil.native_nitrogen} / {soil.native_phosphorus} / {soil.native_potassium} ppm
          </p>
        </div>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Graft Card
// ---------------------------------------------------------------------------

function GraftCard({ graft }: { graft: GraftCombination }) {
  const compatPct = Math.round(graft.compatibility_score * 100);

  return (
    <div className="flex flex-col rounded-2xl border border-stone-200 bg-white p-4 shadow-sm transition hover:shadow-md hover:border-emerald-200 sm:p-5">
      {/* Rootstock → Scion */}
      <div className="mb-4">
        <div className="flex items-center gap-2">
          <div className="min-w-0 flex-1 rounded-lg bg-blue-50 px-3 py-2">
            <p className="text-xs text-blue-500">Rootstock</p>
            <p className="truncate text-xs font-semibold text-blue-900">
              {graft.rootstock.name}
            </p>
          </div>
          <svg
            className="h-4 w-4 shrink-0 text-stone-400"
            fill="none"
            viewBox="0 0 24 24"
            strokeWidth={2}
            stroke="currentColor"
          >
            <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 4.5 21 12m0 0-7.5 7.5M21 12H3" />
          </svg>
          <div className="min-w-0 flex-1 rounded-lg bg-emerald-50 px-3 py-2">
            <p className="text-xs text-emerald-600">Scion</p>
            <p className="truncate text-xs font-semibold text-emerald-900">
              {graft.scion.name}
            </p>
          </div>
        </div>
      </div>

      {/* Compatibility */}
      <div className="mb-4">
        <div className="mb-1 flex items-center justify-between">
          <span className="text-xs text-stone-500">Compatibility</span>
          <span className="text-xs font-semibold text-stone-700">
            {compatPct}%
          </span>
        </div>
        <div className="h-2 rounded-full bg-stone-100">
          <div
            className={`h-2 rounded-full ${
              compatPct >= 80
                ? "bg-emerald-500"
                : compatPct >= 60
                  ? "bg-amber-400"
                  : "bg-red-400"
            }`}
            style={{ width: `${compatPct}%` }}
          />
        </div>
      </div>

      {/* Modifiers */}
      <div className="grid grid-cols-2 gap-2 border-t border-stone-100 pt-3">
        <div className="rounded-xl bg-stone-50 px-3 py-2">
          <p className="text-xs text-stone-400">Vigor Boost</p>
          <p className="text-sm font-semibold text-stone-800">
            {graft.vigor_boost.toFixed(2)}×
          </p>
        </div>
        <div className="rounded-xl bg-stone-50 px-3 py-2">
          <p className="text-xs text-stone-400">Yield Modifier</p>
          <p className="text-sm font-semibold text-stone-800">
            {graft.yield_modifier.toFixed(2)}×
          </p>
        </div>
      </div>

      {graft.notes && (
        <p className="mt-3 text-xs leading-relaxed text-stone-400 line-clamp-2">
          {graft.notes}
        </p>
      )}
    </div>
  );
}

// ---------------------------------------------------------------------------
// Main Browser Component
// ---------------------------------------------------------------------------

type Tab = "plants" | "soils" | "grafts";

interface Props {
  plants: Plant[];
  soils: SoilProfile[];
  grafts: GraftCombination[];
}

export default function DatabaseBrowser({ plants, soils, grafts }: Props) {
  const [activeTab, setActiveTab] = useState<Tab>("plants");
  const [search, setSearch] = useState("");
  const [varietyFilter, setVarietyFilter] = useState<
    "all" | "scion" | "rootstock" | "both"
  >("all");

  const filteredPlants = useMemo(() => {
    const q = search.toLowerCase();
    return plants.filter((p) => {
      const matchesSearch =
        p.name.toLowerCase().includes(q) ||
        p.species.toLowerCase().includes(q);
      const matchesVariety =
        varietyFilter === "all" || p.variety_type === varietyFilter;
      return matchesSearch && matchesVariety;
    });
  }, [plants, search, varietyFilter]);

  const filteredSoils = useMemo(() => {
    const q = search.toLowerCase();
    return soils.filter(
      (s) =>
        s.name.toLowerCase().includes(q) ||
        s.climate_zone.toLowerCase().includes(q) ||
        s.soil_type.toLowerCase().includes(q)
    );
  }, [soils, search]);

  const filteredGrafts = useMemo(() => {
    const q = search.toLowerCase();
    return grafts.filter(
      (g) =>
        g.rootstock.name.toLowerCase().includes(q) ||
        g.scion.name.toLowerCase().includes(q)
    );
  }, [grafts, search]);

  const tabs = [
    { id: "plants" as Tab, label: "Plants", shortLabel: "Plants", count: plants.length },
    { id: "soils" as Tab, label: "Soil Profiles", shortLabel: "Soils", count: soils.length },
    { id: "grafts" as Tab, label: "Graft Combinations", shortLabel: "Grafts", count: grafts.length },
  ];

  return (
    <div>
      {/* Tab bar */}
      <div className="mb-4 sm:mb-6">
        <div className="flex gap-1 rounded-xl border border-stone-200 bg-white p-1 overflow-x-auto no-scrollbar touch-pan-x">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => {
                setActiveTab(tab.id);
                setSearch("");
                setVarietyFilter("all");
              }}
              className={`flex flex-1 sm:flex-none shrink-0 items-center justify-center gap-1.5 sm:gap-2 rounded-lg px-3 py-2 sm:px-4 sm:py-2.5 text-xs sm:text-sm font-bold transition ${
                activeTab === tab.id
                  ? "bg-emerald-800 text-white shadow-md"
                  : "text-stone-600 hover:bg-stone-50 hover:text-stone-900"
              }`}
            >
              <span className="sm:hidden">{tab.shortLabel}</span>
              <span className="hidden sm:inline">{tab.label}</span>
              <span
                className={`rounded-full px-2 py-0.5 text-[10px] font-bold ${
                  activeTab === tab.id
                    ? "bg-white/20 text-white"
                    : "bg-stone-100 text-stone-500"
                }`}
              >
            {tab.count}
              </span>
            </button>
          ))}
        </div>
      </div>

      <div className="mb-4 flex flex-col gap-3 sm:mb-6 sm:gap-4">
        {/* Search */}
        <div className="relative w-full">
          <svg
            className="absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-stone-400"
            fill="none"
            viewBox="0 0 24 24"
            strokeWidth={2}
            stroke="currentColor"
          >
            <path strokeLinecap="round" strokeLinejoin="round" d="m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z" />
          </svg>
          <input
            type="text"
            placeholder={
              activeTab === "plants"
                ? "Search by name or species…"
                : activeTab === "soils"
                  ? "Search by name or climate…"
                  : "Search by rootstock or scion…"
            }
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full rounded-xl border border-stone-200 bg-white py-3 pl-10 pr-4 text-sm text-stone-900 placeholder:text-stone-400 focus:border-emerald-400 focus:outline-none focus:ring-4 focus:ring-emerald-100/50"
          />
        </div>

        {/* Filters — segmented control */}
        {activeTab === "plants" && (
          <div className="flex gap-1 rounded-xl border border-stone-200 bg-white p-1">
            {["all", "scion", "rootstock", "both"].map((v) => (
              <button
                key={v}
                onClick={() => setVarietyFilter(v as any)}
                className={`flex-1 rounded-lg px-2 py-2 text-xs font-semibold transition ${
                  varietyFilter === v
                    ? "bg-emerald-800 text-white shadow-sm"
                    : "text-stone-600 hover:bg-stone-50 hover:text-stone-900"
                }`}
              >
                {v === "all" ? "All" : v.charAt(0).toUpperCase() + v.slice(1)}
              </button>
            ))}
          </div>
        )}
      </div>

      {/* Empty state */}
      {((activeTab === "plants" && filteredPlants.length === 0) ||
        (activeTab === "soils" && filteredSoils.length === 0) ||
        (activeTab === "grafts" && filteredGrafts.length === 0)) && (
        <div className="flex flex-col items-center justify-center rounded-2xl border border-dashed border-stone-200 bg-white py-20 text-center">
          <p className="text-sm font-medium text-stone-500">No results found</p>
          <p className="mt-1 text-xs text-stone-400">
            {search
              ? "Try a different search term."
              : "Start the backend and run the seed script to populate data."}
          </p>
        </div>
      )}

      {/* Cards grid */}
      {activeTab === "plants" && filteredPlants.length > 0 && (
        <div className="grid gap-3 sm:gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
          {filteredPlants.map((p) => (
            <PlantCard key={p.id} plant={p} />
          ))}
        </div>
      )}

      {activeTab === "soils" && filteredSoils.length > 0 && (
        <div className="grid gap-3 sm:gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {filteredSoils.map((s) => (
            <SoilCard key={s.id} soil={s} />
          ))}
        </div>
      )}

      {activeTab === "grafts" && filteredGrafts.length > 0 && (
        <div className="grid gap-3 sm:gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {filteredGrafts.map((g) => (
            <GraftCard key={g.id} graft={g} />
          ))}
        </div>
      )}
    </div>
  );
}
