"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useTags, useCreateTag, useDeleteTag } from "@/lib/hooks";
import { useQueryClient } from "@tanstack/react-query";

const PRESET_COLORS = [
  "#6366f1", "#8b5cf6", "#ec4899", "#ef4444", "#f97316",
  "#eab308", "#22c55e", "#14b8a6", "#3b82f6", "#6b7280",
];

function ConvertModal({
  tag,
  onClose,
}: {
  tag: { id: number; name: string; color: string; transaction_count: number };
  onClose: () => void;
}) {
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [deleteTag, setDeleteTag] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const router = useRouter();
  const qc = useQueryClient();

  async function handleConvert() {
    setSaving(true);
    setError("");
    try {
      const res = await fetch(`/api/tags/${tag.id}/convert-to-trip`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ start_date: startDate || null, end_date: endDate || null }),
      });
      if (!res.ok) throw new Error((await res.json()).error || "Failed");
      const { trip } = await res.json();

      if (deleteTag) {
        await fetch(`/api/tags/${tag.id}`, { method: "DELETE" });
        qc.invalidateQueries({ queryKey: ["tags"] });
      }

      qc.invalidateQueries({ queryKey: ["trips"] });
      router.push(`/trips/${trip.id}`);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Failed to convert");
      setSaving(false);
    }
  }

  return (
    <div className="fixed inset-0 z-40 flex items-center justify-center bg-black/60" onClick={onClose}>
      <div
        className="bg-zinc-900 border border-zinc-700 rounded-xl w-full max-w-sm mx-4 shadow-2xl"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="px-6 pt-5 pb-4 border-b border-zinc-800">
          <div className="flex items-center gap-2">
            <span className="w-3 h-3 rounded-full flex-shrink-0" style={{ backgroundColor: tag.color }} />
            <h3 className="font-semibold text-sm text-zinc-300">Convert "{tag.name}" to Trip</h3>
          </div>
          <p className="text-xs text-zinc-500 mt-1">
            Creates a trip with the same name and color, and assigns all {tag.transaction_count} tagged transaction{tag.transaction_count !== 1 ? "s" : ""} to it.
          </p>
        </div>

        <div className="px-6 py-4 space-y-4">
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs text-zinc-500 mb-1">Start Date</label>
              <input
                type="date"
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
                className="w-full bg-zinc-800 border border-zinc-700 rounded px-2 py-1.5 text-sm focus:outline-none focus:border-zinc-500"
              />
            </div>
            <div>
              <label className="block text-xs text-zinc-500 mb-1">End Date</label>
              <input
                type="date"
                value={endDate}
                onChange={(e) => setEndDate(e.target.value)}
                className="w-full bg-zinc-800 border border-zinc-700 rounded px-2 py-1.5 text-sm focus:outline-none focus:border-zinc-500"
              />
            </div>
          </div>
          <p className="text-xs text-zinc-600">Dates are optional — you can set them later from the trip page.</p>

          <label className="flex items-center gap-2 cursor-pointer select-none">
            <input
              type="checkbox"
              checked={deleteTag}
              onChange={(e) => setDeleteTag(e.target.checked)}
              className="accent-indigo-500"
            />
            <span className="text-sm text-zinc-400">Delete this tag after converting</span>
          </label>
        </div>

        <div className="px-6 py-4 border-t border-zinc-800 flex gap-2 items-center">
          {error && <p className="text-red-400 text-xs mr-auto">{error}</p>}
          <div className="flex gap-2 ml-auto">
            <button
              onClick={onClose}
              className="px-4 py-2 bg-zinc-800 hover:bg-zinc-700 text-zinc-300 rounded-lg text-sm"
            >
              Cancel
            </button>
            <button
              onClick={handleConvert}
              disabled={saving}
              className="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white rounded-lg text-sm font-medium"
            >
              {saving ? "Converting…" : "Convert to Trip"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

export default function TagsPage() {
  const { data: tags, isLoading } = useTags();
  const createTag = useCreateTag();
  const deleteTag = useDeleteTag();

  const [name, setName] = useState("");
  const [color, setColor] = useState(PRESET_COLORS[0]);
  const [error, setError] = useState("");
  const [convertTag, setConvertTag] = useState<{ id: number; name: string; color: string; transaction_count: number } | null>(null);

  const handleCreate = async () => {
    if (!name.trim()) return;
    setError("");
    try {
      await createTag.mutateAsync({ name: name.trim(), color });
      setName("");
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : "Failed to create tag");
    }
  };

  return (
    <div>
      <h2 className="text-2xl font-display mb-4">Tags</h2>

      {/* Create form */}
      <div className="mb-6 p-4 bg-zinc-900/50 border border-zinc-800 rounded-lg">
        <h3 className="text-sm font-medium mb-3">New Tag</h3>
        <div className="flex items-center gap-3 flex-wrap">
          <input
            type="text"
            placeholder="Tag name..."
            value={name}
            onChange={(e) => setName(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && handleCreate()}
            className="bg-zinc-800 border border-zinc-700 rounded px-3 py-1.5 text-sm w-48"
          />
          <div className="flex items-center gap-1.5">
            {PRESET_COLORS.map((c) => (
              <button
                key={c}
                onClick={() => setColor(c)}
                className={`w-5 h-5 rounded-full transition-transform ${color === c ? "scale-125 ring-2 ring-white ring-offset-1 ring-offset-zinc-900" : "hover:scale-110"}`}
                style={{ backgroundColor: c }}
              />
            ))}
          </div>
          <button
            disabled={!name.trim() || createTag.isPending}
            onClick={handleCreate}
            className="px-4 py-1.5 bg-indigo-600 hover:bg-indigo-700 disabled:opacity-50 rounded text-sm"
          >
            Add Tag
          </button>
        </div>
        {error && <p className="text-red-400 text-xs mt-2">{error}</p>}
      </div>

      {/* Tags list */}
      {isLoading ? (
        <p className="text-zinc-500">Loading...</p>
      ) : !tags?.length ? (
        <p className="text-zinc-500">No tags yet. Create one above.</p>
      ) : (
        <div className="space-y-1">
          {tags.map((tag) => (
            <div
              key={tag.id}
              className="flex items-center justify-between px-4 py-2.5 bg-zinc-900/50 border border-zinc-800 rounded-lg group"
            >
              <div className="flex items-center gap-3">
                <span className="w-3 h-3 rounded-full flex-shrink-0" style={{ backgroundColor: tag.color }} />
                <span className="text-sm font-medium">{tag.name}</span>
                <span className="text-xs text-zinc-500">
                  {tag.transaction_count} transaction{tag.transaction_count !== 1 ? "s" : ""}
                </span>
              </div>
              <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                <button
                  onClick={() => setConvertTag(tag)}
                  className="text-xs text-zinc-400 hover:text-indigo-400 transition-colors px-2 py-1 rounded hover:bg-zinc-800"
                  title="Convert to Trip"
                >
                  → Trip
                </button>
                <button
                  onClick={() => deleteTag.mutate(tag.id)}
                  className="text-xs text-zinc-600 hover:text-red-400 transition-colors px-2 py-1 rounded hover:bg-zinc-800"
                >
                  Delete
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {convertTag && (
        <ConvertModal tag={convertTag} onClose={() => setConvertTag(null)} />
      )}
    </div>
  );
}
