import Link from 'next/link';
import type { CoffeeItem } from '../hooks/getActiveCoffees';

type Props = {
  coffees: CoffeeItem[];
  loading: boolean;
  error: string | null;
  selections: Record<string, number>;
  bump: Record<string, boolean>;
  selectedPlanCapsules: number;
  totalCapsules: number;
  onToggleCoffee: (id: string) => void;
  onChangeQuantity: (id: string, delta: number) => void;
  title: string;
};

export default function CoffeeSelectionGrid({
  coffees,
  loading,
  error,
  selections,
  bump,
  selectedPlanCapsules,
  totalCapsules,
  onToggleCoffee,
  onChangeQuantity,
  title,
}: Props) {
  return (
    <section className="rounded-[28px] border border-white/80 bg-white/90 p-6 shadow-[0_24px_70px_-40px_rgba(15,23,42,0.3)] backdrop-blur">
      <h2 className="text-lg font-semibold text-slate-900 mb-4">{title}</h2>

      {error && (
        <div className="mb-4 rounded-xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">{error}</div>
      )}

      {loading ? (
        <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
          <div className="h-52 rounded-2xl bg-slate-100 animate-pulse" />
          <div className="h-52 rounded-2xl bg-slate-100 animate-pulse" />
          <div className="h-52 rounded-2xl bg-slate-100 animate-pulse" />
          <div className="h-52 rounded-2xl bg-slate-100 animate-pulse" />
        </div>
      ) : (
        <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
          {coffees.map((coffee) => {
            const active = coffee.id in selections;
            const qty = selections[coffee.id] || 0;
            const remainingCapsules = selectedPlanCapsules - totalCapsules;
            const maxForCoffee = active ? Math.min(120, qty + remainingCapsules) : 0;
            const sliderMax = Math.max(10, maxForCoffee);
            const sliderProgress = sliderMax <= 10
              ? 100
              : Math.min(100, Math.max(0, ((qty - 10) / (sliderMax - 10)) * 100));
            const canAddCoffee = active || remainingCapsules >= 10;

            return (
              <div
                key={coffee.id}
                className={`group rounded-2xl border p-4 shadow-sm transition ${
                  active ? 'border-slate-900/30 bg-slate-50' : 'border-slate-200 bg-white'
                }`}
              >
                <Link href={`/coffee-abonnements/${coffee.id}`} className="block relative overflow-hidden rounded-xl mb-3">
                  {coffee.image ? (
                    <img
                      src={coffee.image}
                      alt={coffee.name}
                      className="h-36 w-full object-cover transition-transform duration-300 group-hover:scale-105"
                      loading="lazy"
                    />
                  ) : (
                    <div className="h-36 w-full bg-slate-100 rounded-xl" />
                  )}
                  <div className="absolute top-2 left-2 rounded-full bg-black/65 px-2 py-0.5 text-[10px] font-semibold text-white">Details</div>
                  <div className="absolute top-2 right-2 flex flex-col items-end gap-1">
                    <span className={`inline-flex items-center justify-center rounded-full text-white text-[11px] font-bold px-3 py-1 shadow-lg ring-2 ring-white/50 backdrop-blur-sm ${
                      active ? 'bg-slate-900' : 'bg-slate-700/90'
                    }`}>
                      EUR {coffee.pricePer10}
                    </span>
                    <span className="text-[10px] font-medium px-2 py-0.5 rounded-full bg-slate-900/90 text-white border border-white/20 shadow-sm backdrop-blur-sm">per 10</span>
                  </div>
                </Link>

                <div className="flex items-start justify-between gap-2">
                  <h3 className="font-semibold text-sm text-slate-900 line-clamp-1">{coffee.name}</h3>
                </div>
                <p className="mt-2 text-xs text-slate-600 leading-relaxed line-clamp-3">{coffee.description}</p>

                <div className="mt-3 flex gap-2">
                  <button
                    type="button"
                    onClick={() => onToggleCoffee(coffee.id)}
                    disabled={!canAddCoffee}
                    className={`flex-1 text-xs font-semibold rounded-xl px-3 py-2 border transition ${
                      active
                        ? 'border-slate-900 text-slate-900 bg-white hover:bg-slate-100'
                        : canAddCoffee
                          ? 'border-slate-300 hover:bg-slate-100 text-slate-700'
                          : 'border-slate-200 bg-slate-100 text-slate-400 cursor-not-allowed'
                    }`}
                  >
                    {active ? 'Remove' : 'Add'}
                  </button>
                  <Link
                    href={`/coffee-abonnements/${coffee.id}`}
                    className="inline-flex items-center text-xs font-semibold rounded-xl px-3 py-2 border border-slate-200 text-slate-600 hover:bg-slate-100 transition"
                  >
                    View
                  </Link>
                </div>

                {active && (
                  <div className="mt-4 flex flex-col gap-3">
                    <div className="flex items-center justify-between">
                      <span className="text-[11px] font-medium text-slate-500">Quantity (10-{maxForCoffee} pcs)</span>
                      <span className={`inline-flex items-center justify-center rounded-full bg-slate-900 text-white px-3 py-1 text-xs font-semibold transition-transform duration-300 ${bump[coffee.id] ? 'scale-110' : 'scale-100'}`}>
                        {qty} pcs
                      </span>
                    </div>
                    <div className="flex items-center gap-2">
                      <button
                        onClick={() => onChangeQuantity(coffee.id, -10)}
                        disabled={qty <= 10}
                        className="h-8 w-14 rounded-full bg-slate-100 hover:bg-slate-200 text-xs font-medium transition active:scale-95"
                      >
                        -10
                      </button>
                      <div className="flex-1 relative">
                        <input
                          type="range"
                          min={10}
                          max={sliderMax}
                          step={10}
                          value={qty}
                          onChange={(e) => onChangeQuantity(coffee.id, parseInt(e.target.value, 10) - qty)}
                          className="w-full appearance-none cursor-pointer bg-transparent"
                          style={{
                            background:
                              'linear-gradient(to right,#0f172a 0%,#0f172a ' +
                              sliderProgress +
                              '%,#e2e8f0 ' +
                              sliderProgress +
                              '%,#e2e8f0 100%)',
                            height: '6px',
                            borderRadius: '999px',
                          }}
                        />
                      </div>
                      <button
                        onClick={() => onChangeQuantity(coffee.id, +10)}
                        disabled={qty + 10 > maxForCoffee}
                        className="h-8 w-14 rounded-full bg-slate-100 hover:bg-slate-200 text-xs font-medium transition active:scale-95"
                      >
                        +10
                      </button>
                    </div>
                    <div className="flex items-center justify-between text-[11px] text-slate-500">
                      <span>Subtotal</span>
                      <span className="font-semibold text-slate-700">EUR {((qty / 10) * coffee.pricePer10).toFixed(2)}</span>
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </section>
  );
}
