"use client";

import { useState } from "react";

interface CreateTabProps {
  classId: string;
  onCreated: () => void;
}

export function CreateTab({ classId, onCreated }: CreateTabProps) {
  const [deckName, setDeckName] = useState("");
  const [description, setDescription] = useState("");
  const [cards, setCards] = useState([
    { id: "1", front: "", back: "" },
    { id: "2", front: "", back: "" },
    { id: "3", front: "", back: "" },
  ]);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  function addCard() {
    setCards([
      ...cards,
      { id: Date.now().toString(), front: "", back: "" },
    ]);
  }

  function removeCard(id: string) {
    if (cards.length <= 1) return;
    setCards(cards.filter((c) => c.id !== id));
  }

  function updateCard(id: string, field: "front" | "back", value: string) {
    setCards(
      cards.map((c) => (c.id === id ? { ...c, [field]: value } : c))
    );
  }

  async function handleCreate() {
    setError(null);
    if (!deckName.trim()) {
      setError("Deck title is required.");
      return;
    }

    const validCards = cards.filter((c) => c.front.trim() && c.back.trim());
    if (validCards.length === 0) {
      setError("Please add at least one complete card.");
      return;
    }

    setSaving(true);
    try {
      const res = await fetch("/api/decks", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          classId,
          name: deckName,
          data: {
            type: "flashcards",
            deckName: deckName,
            description: description || undefined,
            cards: validCards.map((c) => ({
              front: c.front,
              back: c.back,
            })),
          },
        }),
      });

      if (!res.ok) {
        throw new Error("Failed to create deck");
      }

      onCreated();
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "Failed to create deck");
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="space-y-6">
      {error && (
        <div className="p-3 bg-error-bg text-error rounded-lg text-sm">
          {error}
        </div>
      )}

      {/* Deck Metadata */}
      <div className="space-y-4">
        <div>
          <label className="block text-sm font-medium text-text-heading mb-1">
            Title
          </label>
          <input
            type="text"
            value={deckName}
            onChange={(e) => setDeckName(e.target.value)}
            placeholder="Enter a title, e.g. Biology Ch. 1"
            className="w-full px-4 py-2.5 rounded-lg border border-border bg-bg-surface-alt/50 text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all duration-200"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-text-heading mb-1">
            Description (optional)
          </label>
          <input
            type="text"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            placeholder="Add a description..."
            className="w-full px-4 py-2.5 rounded-lg border border-border bg-bg-surface-alt/50 text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all duration-200"
          />
        </div>
      </div>

      {/* Cards */}
      <div className="space-y-4">
        {cards.map((card, index) => (
          <div
            key={card.id}
            className="bg-bg-surface-alt rounded-xl border border-border-light overflow-hidden"
          >
            <div className="flex items-center justify-between px-4 py-2 border-b border-border-light bg-bg-base/50">
              <span className="font-semibold text-text-muted">{index + 1}</span>
              <button
                onClick={() => removeCard(card.id)}
                disabled={cards.length <= 1}
                className="p-1.5 text-text-muted hover:text-error transition-colors disabled:opacity-30 cursor-pointer"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                </svg>
              </button>
            </div>
            <div className="p-4 grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <input
                  type="text"
                  value={card.front}
                  onChange={(e) => updateCard(card.id, "front", e.target.value)}
                  placeholder="Enter term"
                  className="w-full px-0 py-2 bg-transparent border-0 border-b-2 border-border-light focus:border-primary focus:ring-0 text-sm transition-colors outline-none"
                />
                <span className="block mt-1 text-[10px] font-semibold tracking-wider text-text-muted uppercase">
                  Term
                </span>
              </div>
              <div>
                <input
                  type="text"
                  value={card.back}
                  onChange={(e) => updateCard(card.id, "back", e.target.value)}
                  placeholder="Enter definition"
                  className="w-full px-0 py-2 bg-transparent border-0 border-b-2 border-border-light focus:border-primary focus:ring-0 text-sm transition-colors outline-none"
                />
                <span className="block mt-1 text-[10px] font-semibold tracking-wider text-text-muted uppercase">
                  Definition
                </span>
              </div>
            </div>
          </div>
        ))}
      </div>

      <div className="flex flex-col items-center gap-4 pt-4">
        <button
          onClick={addCard}
          className="px-6 py-2.5 rounded-full bg-bg-surface-alt border border-border-light text-sm font-medium text-text-heading hover:bg-bg-callout transition-colors cursor-pointer"
        >
          + Add a card
        </button>

        <button
          onClick={handleCreate}
          disabled={saving}
          className="w-full md:w-auto px-8 py-3 rounded-lg bg-primary text-white font-medium hover:bg-primary-hover transition-colors cursor-pointer disabled:opacity-50"
        >
          {saving ? "Creating..." : "Create"}
        </button>
      </div>
    </div>
  );
}
