"use client";

import { useState, useTransition } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { deletePlant, addPlantImage, removePlantImage, setPrimaryImage } from "../server/actions";
import type { CalendarDto } from "../server/calendar-bridge";
import type { CareLogDto, CareScheduleDto, PlantDetailDto } from "../server/queries";
import { ShareButton } from "@/components/share-button";
import { ShareLinkList } from "@/components/share-link-list";
import type { EntityShareLink } from "@/modules/_core/share";
import { CareHistoryList } from "./care-history-list";
import { CareLogForm } from "./care-log-form";
import { CareScheduleEditor } from "./care-schedule-editor";

type Tab = "info" | "gallery" | "care";

type Props = {
  plant: PlantDetailDto;
  careLogs: CareLogDto[];
  careSchedules: CareScheduleDto[];
  calendars: CalendarDto[];
  shareLinks: EntityShareLink[];
};

function InfoRow({
  label,
  value,
  children,
}: {
  label: string;
  value?: string | null;
  children?: React.ReactNode;
}) {
  if (!value && !children) return null;
  return (
    <div className="flex gap-3">
      <span className="text-sm text-[var(--ink-mute)] w-28 shrink-0">{label}</span>
      <span className="text-sm">{children ?? value}</span>
    </div>
  );
}

function healthBadgeClass(status: string): string {
  if (status === "healthy") return "badge-success";
  if (status === "sick") return "badge-danger";
  return "badge-warning";
}

export function PlantDetail({ plant, careLogs, careSchedules, calendars, shareLinks }: Props) {
  const [tab, setTab] = useState<Tab>("info");
  const [confirming, setConfirming] = useState(false);
  const [isPending, startTransition] = useTransition();
  const [galleryError, setGalleryError] = useState<string | null>(null);
  const [uploadingImage, setUploadingImage] = useState(false);
  const router = useRouter();

  function handleDelete() {
    startTransition(async () => {
      await deletePlant({ id: plant.id });
      router.push("/garden");
      router.refresh();
    });
  }

  async function handleImageUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setGalleryError(null);
    setUploadingImage(true);
    try {
      const fd = new FormData();
      fd.append("file", file);
      const res = await fetch("/api/uploads", { method: "POST", body: fd });
      if (!res.ok) throw new Error("Upload failed");
      const data = (await res.json()) as { url: string };
      await addPlantImage({ id: plant.id, url: data.url });
      router.refresh();
    } catch {
      setGalleryError("Image upload failed.");
    } finally {
      setUploadingImage(false);
      e.target.value = "";
    }
  }

  function handleRemoveImage(url: string) {
    startTransition(async () => {
      await removePlantImage({ id: plant.id, url });
      router.refresh();
    });
  }

  function handleSetPrimary(url: string) {
    startTransition(async () => {
      await setPrimaryImage({ id: plant.id, url });
      router.refresh();
    });
  }

  return (
    <div className="flex flex-col gap-5">
      {/* Header */}
      <div className="flex items-start justify-between gap-4">
        <div className="flex items-start gap-4">
          {plant.primaryImageUrl && (
            <img
              src={plant.primaryImageUrl}
              alt=""
              className="w-16 h-16 rounded-lg object-cover shrink-0"
            />
          )}
          <div>
            <h1 className="text-2xl font-bold">{plant.name}</h1>
            {plant.scientificName && (
              <p className="text-sm text-[var(--ink-mute)] italic mt-0.5">{plant.scientificName}</p>
            )}
            <div className="flex flex-wrap gap-2 mt-1">
              <span className={`text-xs badge ${healthBadgeClass(plant.healthStatus)}`}>
                {plant.healthStatus}
              </span>
              {plant.growthStage && (
                <span className="text-xs badge badge-outline capitalize">{plant.growthStage}</span>
              )}
            </div>
          </div>
        </div>

        <div className="flex flex-col items-end gap-2 shrink-0">
          <div className="flex gap-2">
            <ShareButton entityType="garden.plant" entityId={plant.id} />
            <Link href={`/garden/plants/${plant.id}/edit`} className="btn btn-ghost btn-sm">
              Edit
            </Link>
            {confirming ? (
              <div className="flex gap-1">
                <button
                  className="btn btn-danger btn-sm"
                  onClick={handleDelete}
                  disabled={isPending}
                >
                  Confirm
                </button>
                <button
                  className="btn btn-ghost btn-sm"
                  onClick={() => setConfirming(false)}
                  disabled={isPending}
                >
                  Cancel
                </button>
              </div>
            ) : (
              <button className="btn btn-ghost btn-sm" onClick={() => setConfirming(true)}>
                Delete
              </button>
            )}
          </div>
          <ShareLinkList links={shareLinks} />
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-6 border-b border-[var(--ink-faint)]">
        {(["info", "gallery", "care"] as Tab[]).map((t) => (
          <button
            key={t}
            onClick={() => setTab(t)}
            className={`pb-2 text-sm font-medium capitalize transition-colors ${
              tab === t
                ? "border-b-2 border-[var(--ink)] text-[var(--ink)]"
                : "text-[var(--ink-mute)]"
            }`}
          >
            {t}
          </button>
        ))}
      </div>

      {/* Info */}
      {tab === "info" && (
        <div className="flex flex-col gap-2">
          <InfoRow label="Category" value={plant.category} />
          {plant.containerName && (
            <InfoRow label="Container">
              <Link href={`/garden/containers/${plant.containerId}`} className="underline">
                {plant.containerName}
              </Link>
            </InfoRow>
          )}
          <InfoRow label="Acquired" value={plant.acquisitionDate} />
          <InfoRow label="Sunlight" value={plant.sunlight} />
          <InfoRow label="Watering" value={plant.wateringNotes} />
          <InfoRow label="Fertilizing" value={plant.fertilizingNotes} />
          <InfoRow label="Notes" value={plant.notes} />
          {plant.recentCareLogs.length > 0 && (
            <div className="mt-2">
              <p className="text-xs font-semibold text-[var(--ink-mute)] uppercase tracking-wide mb-1">
                Recent care
              </p>
              <ul className="text-sm space-y-1">
                {plant.recentCareLogs.map((log) => (
                  <li key={log.id} className="flex gap-2 flex-wrap">
                    <span className="capitalize">{log.careType}</span>
                    <span className="text-[var(--ink-mute)]">
                      {new Date(log.performedAt).toLocaleDateString()}
                    </span>
                    {log.notes && <span className="text-[var(--ink-mute)]">— {log.notes}</span>}
                  </li>
                ))}
              </ul>
            </div>
          )}
        </div>
      )}

      {/* Gallery */}
      {tab === "gallery" && (
        <div className="flex flex-col gap-4">
          {plant.images.length === 0 ? (
            <p className="text-sm text-[var(--ink-mute)]">No photos yet.</p>
          ) : (
            <div className="grid grid-cols-3 gap-2">
              {plant.images.map((url) => (
                <div key={url} className="relative group">
                  <img src={url} alt="" className="w-full aspect-square object-cover rounded-lg" />
                  <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 rounded-lg flex items-center justify-center gap-3 transition-opacity">
                    <button
                      onClick={() => handleSetPrimary(url)}
                      disabled={isPending}
                      title="Set as primary"
                      className={`text-lg leading-none ${url === plant.primaryImageUrl ? "text-yellow-400" : "text-white"}`}
                    >
                      ★
                    </button>
                    <button
                      onClick={() => handleRemoveImage(url)}
                      disabled={isPending}
                      title="Remove"
                      className="text-white text-lg leading-none"
                    >
                      ✕
                    </button>
                  </div>
                  {url === plant.primaryImageUrl && (
                    <span className="absolute top-1 left-1 text-xs px-1 bg-black/60 text-yellow-300 rounded">
                      Primary
                    </span>
                  )}
                </div>
              ))}
            </div>
          )}

          {galleryError && <p className="text-sm text-red-500">{galleryError}</p>}

          <div className="flex items-center gap-3">
            {plant.images.length < 10 && (
              <label className="btn btn-ghost btn-sm cursor-pointer">
                {uploadingImage ? "Uploading…" : "Upload photo"}
                <input
                  type="file"
                  accept="image/*"
                  className="hidden"
                  onChange={handleImageUpload}
                  disabled={uploadingImage}
                />
              </label>
            )}
            <span className="text-xs text-[var(--ink-mute)]">{plant.images.length}/10 photos</span>
          </div>
        </div>
      )}

      {/* Care */}
      {tab === "care" && (
        <div className="flex flex-col gap-6">
          <CareScheduleEditor plantId={plant.id} schedules={careSchedules} calendars={calendars} />
          <div className="border-t border-[var(--ink-faint)] pt-4">
            <p className="text-sm font-semibold text-[var(--ink-mute)] uppercase tracking-wide mb-3">
              Log care
            </p>
            <CareLogForm plantId={plant.id} onSuccess={() => router.refresh()} />
          </div>
          <div className="border-t border-[var(--ink-faint)] pt-4">
            <p className="text-sm font-semibold text-[var(--ink-mute)] uppercase tracking-wide mb-3">
              History
            </p>
            <CareHistoryList logs={careLogs} />
          </div>
        </div>
      )}
    </div>
  );
}
