"use client";

import { useState, FormEvent } from "react";
import { useRouter } from "next/navigation";
import styles from "../../admin.module.css";

interface Category {
  id: string;
  name: string;
}

interface AppFormData {
  name: string;
  slug: string;
  shortDescription: string;
  description: string;
  type: string;
  status: string;
  featured: boolean;
  order: number;
  icon: string;
  screenshots: string;
  features: string;
  tags: string;
  appUrl: string;
  chromeStoreUrl: string;
  firefoxStoreUrl: string;
  downloadUrl: string;
  version: string;
  categoryId: string;
}

interface AppFormProps {
  categories: Category[];
  initialData?: Partial<AppFormData>;
  appId?: string;
  mode: "new" | "edit";
}

function slugify(str: string) {
  return str.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "");
}

export default function AppForm({ categories, initialData, appId, mode }: AppFormProps) {
  const router = useRouter();
  const [saving, setSaving] = useState(false);
  const [success, setSuccess] = useState("");
  const [error, setError] = useState("");

  const [form, setForm] = useState<AppFormData>({
    name: initialData?.name ?? "",
    slug: initialData?.slug ?? "",
    shortDescription: initialData?.shortDescription ?? "",
    description: initialData?.description ?? "",
    type: initialData?.type ?? "web",
    status: initialData?.status ?? "draft",
    featured: initialData?.featured ?? false,
    order: initialData?.order ?? 0,
    icon: initialData?.icon ?? "",
    screenshots: initialData?.screenshots ?? "",
    features: initialData?.features ?? "",
    tags: initialData?.tags ?? "",
    appUrl: initialData?.appUrl ?? "",
    chromeStoreUrl: initialData?.chromeStoreUrl ?? "",
    firefoxStoreUrl: initialData?.firefoxStoreUrl ?? "",
    downloadUrl: initialData?.downloadUrl ?? "",
    version: initialData?.version ?? "",
    categoryId: initialData?.categoryId ?? "",
  });

  const handleChange = (field: keyof AppFormData, value: string | boolean | number) => {
    setForm((prev) => ({ ...prev, [field]: value }));
    if (field === "name" && mode === "new") {
      setForm((prev) => ({ ...prev, slug: slugify(value as string) }));
    }
  };

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setError("");
    setSuccess("");

    const parseJsonArray = (str: string): string[] => {
      if (!str.trim()) return [];
      try {
        const parsed = JSON.parse(str);
        if (Array.isArray(parsed)) return parsed;
      } catch {}
      return str.split("\n").map((s) => s.trim()).filter(Boolean);
    };

    const payload = {
      ...form,
      screenshots: parseJsonArray(form.screenshots),
      features: parseJsonArray(form.features),
      tags: parseJsonArray(form.tags),
      order: Number(form.order),
      categoryId: form.categoryId || null,
      icon: form.icon || null,
      appUrl: form.appUrl || null,
      chromeStoreUrl: form.chromeStoreUrl || null,
      firefoxStoreUrl: form.firefoxStoreUrl || null,
      downloadUrl: form.downloadUrl || null,
      version: form.version || null,
    };

    const url = mode === "edit" ? `/api/admin/apps/${appId}` : "/api/admin/apps";
    const method = mode === "edit" ? "PUT" : "POST";

    try {
      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error ?? "Something went wrong");
      }

      setSuccess(mode === "edit" ? "App updated successfully!" : "App created successfully!");
      if (mode === "new") {
        router.push("/admin/apps");
      }
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "Failed to save app.");
    } finally {
      setSaving(false);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      {success && <div className={styles.alertSuccess}>✅ {success}</div>}
      {error && <div className={styles.alertError}>❌ {error}</div>}

      <div className={styles.formCard}>
        <h3 style={{ color: "#e2e8f0", marginBottom: "20px", fontSize: "15px", fontWeight: 600 }}>Basic Information</h3>
        <div className={styles.formGrid}>
          <div className={styles.formGroup}>
            <label className={styles.formLabel}>App Name *</label>
            <input
              className={styles.formInput}
              required
              value={form.name}
              onChange={(e) => handleChange("name", e.target.value)}
              placeholder="OxyCoder Inspect"
            />
          </div>

          <div className={styles.formGroup}>
            <label className={styles.formLabel}>Slug *</label>
            <input
              className={styles.formInput}
              required
              value={form.slug}
              onChange={(e) => handleChange("slug", e.target.value)}
              placeholder="oxycoder-inspect"
            />
            <span className={styles.formHint}>Used in the URL: /app/your-slug</span>
          </div>

          <div className={`${styles.formGroup} ${styles.formFullWidth}`}>
            <label className={styles.formLabel}>Short Description *</label>
            <input
              className={styles.formInput}
              required
              value={form.shortDescription}
              onChange={(e) => handleChange("shortDescription", e.target.value)}
              placeholder="A brief one-liner that appears in the directory listing"
            />
          </div>

          <div className={`${styles.formGroup} ${styles.formFullWidth}`}>
            <label className={styles.formLabel}>Full Description *</label>
            <textarea
              className={styles.formTextarea}
              required
              style={{ minHeight: 140 }}
              value={form.description}
              onChange={(e) => handleChange("description", e.target.value)}
              placeholder="Write a detailed description of the app, its features, and use cases..."
            />
          </div>

          <div className={styles.formGroup}>
            <label className={styles.formLabel}>App Type *</label>
            <select className={styles.formSelect} value={form.type} onChange={(e) => handleChange("type", e.target.value)}>
              <option value="web">Web App</option>
              <option value="chrome-extension">Chrome Extension</option>
              <option value="firefox-extension">Firefox Extension</option>
              <option value="desktop">Desktop App</option>
            </select>
          </div>

          <div className={styles.formGroup}>
            <label className={styles.formLabel}>Category</label>
            <select className={styles.formSelect} value={form.categoryId} onChange={(e) => handleChange("categoryId", e.target.value)}>
              <option value="">No Category</option>
              {categories.map((cat) => (
                <option key={cat.id} value={cat.id}>{cat.name}</option>
              ))}
            </select>
          </div>

          <div className={styles.formGroup}>
            <label className={styles.formLabel}>Status</label>
            <select className={styles.formSelect} value={form.status} onChange={(e) => handleChange("status", e.target.value)}>
              <option value="draft">Draft</option>
              <option value="published">Published</option>
            </select>
          </div>

          <div className={styles.formGroup}>
            <label className={styles.formLabel}>Sort Order</label>
            <input
              type="number"
              className={styles.formInput}
              value={form.order}
              onChange={(e) => handleChange("order", e.target.value)}
              placeholder="0"
            />
          </div>

          <div className={`${styles.formGroup} ${styles.formFullWidth}`}>
            <label className={styles.formLabel}>Featured</label>
            <div className={styles.formCheckboxRow}>
              <input
                type="checkbox"
                id="featured"
                className={styles.formCheckbox}
                checked={form.featured}
                onChange={(e) => handleChange("featured", e.target.checked)}
              />
              <label htmlFor="featured" style={{ fontSize: 13, color: "#94a3b8", cursor: "pointer" }}>
                Mark this app as featured (shown first in the directory)
              </label>
            </div>
          </div>
        </div>
      </div>

      <div className={styles.formCard} style={{ marginTop: 16 }}>
        <h3 style={{ color: "#e2e8f0", marginBottom: "20px", fontSize: "15px", fontWeight: 600 }}>Media & Links</h3>
        <div className={styles.formGrid}>
          <div className={`${styles.formGroup} ${styles.formFullWidth}`}>
            <label className={styles.formLabel}>Icon URL</label>
            <input
              className={styles.formInput}
              value={form.icon}
              onChange={(e) => handleChange("icon", e.target.value)}
              placeholder="https://example.com/icon.png"
            />
          </div>

          <div className={`${styles.formGroup} ${styles.formFullWidth}`}>
            <label className={styles.formLabel}>Screenshots (one URL per line or JSON array)</label>
            <textarea
              className={styles.formTextarea}
              value={form.screenshots}
              onChange={(e) => handleChange("screenshots", e.target.value)}
              placeholder={"https://example.com/screenshot1.png\nhttps://example.com/screenshot2.png"}
            />
          </div>

          <div className={styles.formGroup}>
            <label className={styles.formLabel}>Web App URL</label>
            <input className={styles.formInput} value={form.appUrl} onChange={(e) => handleChange("appUrl", e.target.value)} placeholder="https://app.example.com" />
          </div>

          <div className={styles.formGroup}>
            <label className={styles.formLabel}>Chrome Store URL</label>
            <input className={styles.formInput} value={form.chromeStoreUrl} onChange={(e) => handleChange("chromeStoreUrl", e.target.value)} placeholder="https://chrome.google.com/webstore/..." />
          </div>

          <div className={styles.formGroup}>
            <label className={styles.formLabel}>Firefox Store URL</label>
            <input className={styles.formInput} value={form.firefoxStoreUrl} onChange={(e) => handleChange("firefoxStoreUrl", e.target.value)} placeholder="https://addons.mozilla.org/..." />
          </div>

          <div className={styles.formGroup}>
            <label className={styles.formLabel}>Download URL</label>
            <input className={styles.formInput} value={form.downloadUrl} onChange={(e) => handleChange("downloadUrl", e.target.value)} placeholder="https://example.com/download.exe" />
          </div>

          <div className={styles.formGroup}>
            <label className={styles.formLabel}>Version</label>
            <input className={styles.formInput} value={form.version} onChange={(e) => handleChange("version", e.target.value)} placeholder="1.0.0" />
          </div>
        </div>
      </div>

      <div className={styles.formCard} style={{ marginTop: 16 }}>
        <h3 style={{ color: "#e2e8f0", marginBottom: "20px", fontSize: "15px", fontWeight: 600 }}>Features & Tags</h3>
        <div className={styles.formGrid}>
          <div className={`${styles.formGroup} ${styles.formFullWidth}`}>
            <label className={styles.formLabel}>Features (one per line)</label>
            <textarea
              className={styles.formTextarea}
              value={form.features}
              onChange={(e) => handleChange("features", e.target.value)}
              placeholder={"Real-time collaboration\nDark mode support\nOffline access"}
            />
          </div>

          <div className={`${styles.formGroup} ${styles.formFullWidth}`}>
            <label className={styles.formLabel}>Tags (one per line, no # symbol)</label>
            <textarea
              className={styles.formTextarea}
              value={form.tags}
              onChange={(e) => handleChange("tags", e.target.value)}
              placeholder={"productivity\nnotes\nmarkdown"}
            />
          </div>
        </div>
      </div>

      <div className={styles.formActions}>
        <button type="submit" disabled={saving} className={styles.btnPrimary} style={{ minWidth: 140 }}>
          {saving ? "Saving..." : mode === "edit" ? "💾 Save Changes" : "🚀 Create App"}
        </button>
        <a href="/admin/apps" className={styles.btnSecondary}>Cancel</a>
      </div>
    </form>
  );
}
