import { Upload, X, Plus, CircleDollarSign } from "lucide-react";
import { cn } from "../../lib/utils";
import {
  type Draft,
  type EffectDraft,
  type ItemType,
  type ItemRarity,
  TYPE_META,
  RARITY_META,
  inputCls,
} from "./ItemStudioTypes";
import { SectionCard, Field } from "./ItemStudioShared";
import { EffectEditor } from "./EffectEditor";

// ===== Item Studio Form Sections =====

export function IdentitySection({
  draft,
  update,
  validationErrors,
}: {
  draft: Draft;
  update: (fields: Partial<Draft>) => void;
  validationErrors: Record<string, string>;
}) {
  return (
    <SectionCard title="Identity">
      <Field label="Item Name *" error={validationErrors.name}>
        <input
          type="text"
          value={draft.name}
          onChange={(e) => update({ name: e.target.value })}
          placeholder="e.g. Treasure Chest"
          maxLength={255}
          className={cn(
            inputCls,
            validationErrors.name &&
              "border-destructive focus:border-destructive focus:ring-destructive/30"
          )}
        />
      </Field>
      <Field label="Description">
        <textarea
          value={draft.description}
          onChange={(e) => update({ description: e.target.value })}
          placeholder="A brief description of this item..."
          rows={3}
          className={cn(inputCls, "resize-none")}
        />
      </Field>
    </SectionCard>
  );
}

export function ClassificationSection({
  draft,
  update,
}: {
  draft: Draft;
  update: (fields: Partial<Draft>) => void;
}) {
  return (
    <SectionCard title="Classification">
      <Field label="Type">
        <div className="grid grid-cols-4 gap-2">
          {(Object.keys(TYPE_META) as ItemType[]).map((t) => {
            const meta = TYPE_META[t];
            const Icon = meta.icon;
            const active = draft.type === t;
            return (
              <button
                key={t}
                onClick={() => update({ type: t })}
                className={cn(
                  "flex flex-col items-center gap-1.5 py-3 px-2 rounded-lg border text-xs font-medium transition-all",
                  active
                    ? "bg-primary/15 border-primary text-primary"
                    : "bg-input border-border text-text-tertiary hover:border-primary/40 hover:text-foreground"
                )}
              >
                <Icon className="w-4 h-4" />
                {meta.label}
              </button>
            );
          })}
        </div>
      </Field>

      <Field label="Rarity">
        <div className="grid grid-cols-4 gap-2">
          {(Object.keys(RARITY_META) as ItemRarity[]).map((r) => {
            const meta = RARITY_META[r];
            const active = draft.rarity === r;
            return (
              <button
                key={r}
                onClick={() => update({ rarity: r })}
                className={cn(
                  "py-3 px-2 rounded-lg border text-center transition-all",
                  active
                    ? cn(meta.bg, meta.text, meta.activeBorder)
                    : "bg-input border-border text-text-tertiary hover:border-primary/40"
                )}
              >
                <div className="text-sm font-bold">{r}</div>
                <div
                  className={cn(
                    "text-xs mt-0.5 opacity-80",
                    active ? meta.text : "text-text-disabled"
                  )}
                >
                  {meta.label}
                </div>
              </button>
            );
          })}
        </div>
      </Field>
    </SectionCard>
  );
}

export function EconomySection({
  draft,
  update,
}: {
  draft: Draft;
  update: (fields: Partial<Draft>) => void;
}) {
  return (
    <SectionCard title="Economy">
      <Field label="Price (0 or empty = not for sale)">
        <div className="relative">
          <CircleDollarSign className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-text-tertiary pointer-events-none" />
          <input
            type="number"
            min="0"
            step="1"
            value={draft.price}
            onChange={(e) => update({ price: e.target.value })}
            placeholder="0"
            className={cn(inputCls, "pl-10")}
          />
        </div>
      </Field>
    </SectionCard>
  );
}

export function ArtworkSection({
  imageMode,
  setImageMode,
  imageFile,
  imagePreview,
  iconUrlInput,
  setIconUrlInput,
  imageUrlInput,
  setImageUrlInput,
  dragOver,
  setDragOver,
  handleDrop,
  clearImage,
  handleImageFile,
  fileInputRef,
  validationErrors,
}: {
  imageMode: "upload" | "url";
  setImageMode: (mode: "upload" | "url") => void;
  imageFile: File | null;
  imagePreview: string | null;
  iconUrlInput: string;
  setIconUrlInput: (v: string) => void;
  imageUrlInput: string;
  setImageUrlInput: (v: string) => void;
  dragOver: boolean;
  setDragOver: (v: boolean) => void;
  handleDrop: (e: React.DragEvent) => void;
  clearImage: () => void;
  handleImageFile: (file: File) => void;
  fileInputRef: React.RefObject<HTMLInputElement | null>;
  validationErrors: Record<string, string>;
}) {
  return (
    <SectionCard title="Artwork">
      <div className="flex gap-2">
        {(["upload", "url"] as const).map((mode) => (
          <button
            key={mode}
            onClick={() => setImageMode(mode)}
            className={cn(
              "px-3 py-1.5 rounded-md text-xs font-medium transition-colors border",
              imageMode === mode
                ? "bg-primary/15 border-primary text-primary"
                : "bg-input border-border text-text-tertiary hover:text-foreground"
            )}
          >
            {mode === "upload" ? "Upload File" : "Enter URL"}
          </button>
        ))}
      </div>

      {imageMode === "upload" ? (
        <div className="space-y-2">
          {imageFile ? (
            <div className="relative rounded-lg overflow-hidden border border-border">
              <img
                src={imagePreview!}
                alt="Selected"
                className="w-full max-h-56 object-contain bg-raised"
              />
              <button
                onClick={clearImage}
                className="absolute top-2 right-2 p-1.5 bg-background/80 rounded-full hover:bg-destructive hover:text-white text-text-secondary transition-colors backdrop-blur-sm"
              >
                <X className="w-4 h-4" />
              </button>
              <div className="px-3 py-2 bg-card border-t border-border">
                <p className="text-xs text-text-tertiary truncate">
                  {imageFile.name} ({(imageFile.size / 1024).toFixed(1)}{" "}
                  KB)
                </p>
              </div>
            </div>
          ) : (
            <div
              onDrop={handleDrop}
              onDragOver={(e) => {
                e.preventDefault();
                setDragOver(true);
              }}
              onDragLeave={() => setDragOver(false)}
              onClick={() => fileInputRef.current?.click()}
              className={cn(
                "border-2 border-dashed rounded-lg p-10 flex flex-col items-center gap-3 cursor-pointer transition-all select-none",
                dragOver
                  ? "border-primary bg-primary/5"
                  : "border-border hover:border-primary/50 hover:bg-primary/3"
              )}
            >
              <Upload
                className={cn(
                  "w-8 h-8 transition-colors",
                  dragOver ? "text-primary" : "text-text-tertiary"
                )}
              />
              <div className="text-center">
                <p className="text-sm font-medium text-text-secondary">
                  {dragOver ? "Drop to upload" : "Drop an image here"}
                </p>
                <p className="text-xs text-text-tertiary mt-1">
                  or click to browse · PNG, JPEG, WebP, GIF · max 15 MB
                </p>
              </div>
            </div>
          )}
          {validationErrors.image && (
            <p className="text-xs text-destructive">
              {validationErrors.image}
            </p>
          )}
          <input
            ref={fileInputRef}
            type="file"
            accept="image/png,image/jpeg,image/webp,image/gif"
            onChange={(e) => {
              const file = e.target.files?.[0];
              if (file) handleImageFile(file);
            }}
            className="hidden"
          />
        </div>
      ) : (
        <div className="space-y-3">
          <Field
            label="Icon URL (small, used in lists)"
            error={validationErrors.iconUrl}
          >
            <input
              type="url"
              value={iconUrlInput}
              onChange={(e) => setIconUrlInput(e.target.value)}
              placeholder="https://example.com/icon.png"
              className={inputCls}
            />
          </Field>
          <Field
            label="Image URL (full size)"
            error={validationErrors.imageUrl}
          >
            <input
              type="url"
              value={imageUrlInput}
              onChange={(e) => setImageUrlInput(e.target.value)}
              placeholder="https://example.com/image.png"
              className={inputCls}
            />
          </Field>
          {iconUrlInput && (
            <div className="flex items-center gap-3 p-3 bg-raised/40 rounded-lg border border-border">
              <img
                src={iconUrlInput}
                alt="Icon preview"
                className="w-10 h-10 rounded object-cover bg-raised"
                onError={(e) => {
                  e.currentTarget.style.opacity = "0.2";
                }}
              />
              <span className="text-xs text-text-tertiary">
                Icon preview
              </span>
            </div>
          )}
        </div>
      )}
    </SectionCard>
  );
}

export function EffectsSection({
  draft,
  update,
  updateEffect,
  removeEffect,
  addEffect,
}: {
  draft: Draft;
  update: (fields: Partial<Draft>) => void;
  updateEffect: (i: number, updated: EffectDraft) => void;
  removeEffect: (i: number) => void;
  addEffect: () => void;
}) {
  return (
    <SectionCard title="Effects">
      <label className="flex items-center gap-3 cursor-pointer group select-none">
        <button
          role="switch"
          aria-checked={draft.consume}
          onClick={() => update({ consume: !draft.consume })}
          className={cn(
            "relative w-10 h-5 rounded-full border transition-all shrink-0",
            draft.consume
              ? "bg-primary border-primary"
              : "bg-input border-border"
          )}
        >
          <span
            className={cn(
              "absolute top-0.5 w-4 h-4 rounded-full bg-white shadow-sm transition-all duration-200",
              draft.consume ? "left-5" : "left-0.5"
            )}
          />
        </button>
        <span className="text-sm text-text-secondary group-hover:text-foreground transition-colors">
          Consume item on use
        </span>
      </label>

      {draft.effects.map((eff, i) => (
        <EffectEditor
          key={eff._id}
          effect={eff}
          onChange={(updated) => updateEffect(i, updated)}
          onRemove={() => removeEffect(i)}
        />
      ))}

      <button
        onClick={addEffect}
        className={cn(
          "w-full flex items-center justify-center gap-2 py-2.5 rounded-lg border border-dashed text-sm",
          "border-border text-text-tertiary hover:border-primary/50 hover:text-primary transition-colors"
        )}
      >
        <Plus className="w-4 h-4" />
        Add Effect
      </button>
    </SectionCard>
  );
}
