"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Container } from "lucide-react";
import {
  Empty,
  EmptyDescription,
  EmptyHeader,
  EmptyMedia,
  EmptyTitle,
} from "@/components/ui/empty";
import { ContainerForm } from "./container-form";
import type { ContainerDto } from "../server/queries";

type Props = { containers: ContainerDto[] };

export function ContainerList({ containers }: Props) {
  const [showNew, setShowNew] = useState(false);
  const router = useRouter();

  return (
    <div className="flex flex-col gap-4">
      <div className="flex items-center justify-between">
        <h2 className="text-lg font-semibold">Containers</h2>
        <button className="btn btn-primary btn-sm" onClick={() => setShowNew(true)}>
          New container
        </button>
      </div>

      {showNew && (
        <div className="card p-4">
          <h3 className="font-medium mb-3">New container</h3>
          <ContainerForm
            onSuccess={() => {
              setShowNew(false);
              router.refresh();
            }}
            onCancel={() => setShowNew(false)}
          />
        </div>
      )}

      {containers.length === 0 && !showNew && (
        <Empty className="border-none">
          <EmptyHeader>
            <EmptyMedia variant="icon">
              <Container />
            </EmptyMedia>
            <EmptyTitle>No containers yet</EmptyTitle>
            <EmptyDescription>Add a container to start organising your plants.</EmptyDescription>
          </EmptyHeader>
        </Empty>
      )}

      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
        {containers.map((c) => (
          <Link
            key={c.id}
            href={`/garden/containers/${c.id}`}
            className="card p-4 hover:bg-[var(--surface-2)] transition-colors"
          >
            {c.coverImageUrl && (
              <img src={c.coverImageUrl} alt="" className="w-full h-32 object-cover rounded mb-3" />
            )}
            <div className="flex items-start justify-between gap-2">
              <span className="font-medium leading-tight">{c.name}</span>
              <span className="badge badge-outline text-xs shrink-0 capitalize">{c.type}</span>
            </div>
            <p className="text-sm text-[var(--ink-mute)] mt-1">
              {c.plantCount} {c.plantCount === 1 ? "plant" : "plants"}
            </p>
          </Link>
        ))}
      </div>
    </div>
  );
}
