"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { BlogStatus } from "@prisma/client";
import { createBlog, updateBlog } from "@/lib/actions/blog";
import {
  Save,
  X,
  Plus,
  Trash2,
  ChevronLeft,
  Layout,
  Type,
  FileText,
  Tag as TagIcon,
  Globe,
  Eye,
} from "lucide-react";
import Link from "next/link";
import { cn } from "@/lib/utils";

interface BlogFormProps {
  initialData?: any;
}

export function BlogForm({ initialData }: BlogFormProps) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [tags, setTags] = useState<string[]>(
    initialData?.tags?.map((t: any) => t.name) || [],
  );
  const [tagInput, setTagInput] = useState("");

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setLoading(true);

    try {
      const formData = new FormData(e.currentTarget);
      const data = {
        title: formData.get("title") as string,
        slug: formData.get("slug") as string,
        content: formData.get("content") as string,
        excerpt: formData.get("excerpt") as string,
        status: formData.get("status") as BlogStatus,
        tags: tags,
      };

      if (initialData) {
        await updateBlog(initialData.id, data);
      } else {
        await createBlog(data);
      }

      router.push("/dashboard/blog");
      router.refresh();
    } catch (error) {
      console.error(error);
      alert("Something went wrong. Check the console.");
    } finally {
      setLoading(false);
    }
  }

  const addTag = () => {
    if (tagInput && !tags.includes(tagInput)) {
      setTags([...tags, tagInput]);
      setTagInput("");
    }
  };

  const removeTag = (tagToRemove: string) => {
    setTags(tags.filter((t) => t !== tagToRemove));
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-8 max-w-5xl mx-auto pb-20">
      <div className="flex items-center justify-between gap-4 border-b border-border pb-6">
        <div className="flex items-center gap-4">
          <Link
            href="/dashboard/blog"
            className="p-2 hover:bg-surface-elevated rounded-lg text-foreground-muted transition-colors"
          >
            <ChevronLeft size={20} />
          </Link>
          <div>
            <h1 className="text-2xl font-display font-bold text-foreground">
              {initialData ? "Edit Post" : "Create New Post"}
            </h1>
            <p className="text-sm text-foreground-muted">
              {initialData ? "Make changes to your article." : "Draft a new masterpiece."}
            </p>
          </div>
        </div>
        <div className="flex items-center gap-3">
          <button
            type="button"
            onClick={() => router.back()}
            className="px-4 py-2 border border-border bg-surface text-foreground font-medium rounded-lg hover:bg-surface-elevated transition-all text-sm"
          >
            Cancel
          </button>
          <button
            type="submit"
            disabled={loading}
            className="inline-flex items-center gap-2 px-6 py-2 bg-primary text-primary-foreground font-semibold rounded-lg hover:shadow-lg hover:shadow-primary/20 transition-all disabled:opacity-50 text-sm"
          >
            <Save size={18} />
            {loading ? "Saving..." : initialData ? "Update Changes" : "Publish Post"}
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Main Content */}
        <div className="lg:col-span-2 space-y-6">
          <div className="bg-surface border border-border/50 rounded-2xl p-6 space-y-6 card-shadow">
            <div className="space-y-2">
              <label className="text-sm font-semibold text-foreground flex items-center gap-2">
                <Type size={16} className="text-primary/60" />
                Post Title
              </label>
              <input
                name="title"
                defaultValue={initialData?.title}
                placeholder="Enter a catchy title..."
                required
                className="w-full px-4 py-3 bg-background border border-border/50 rounded-xl focus:ring-2 focus:ring-primary/20 focus:border-primary outline-none transition-all text-lg font-medium"
              />
            </div>

            <div className="space-y-2">
              <label className="text-sm font-semibold text-foreground flex items-center gap-2">
                <Globe size={16} className="text-primary/60" />
                Slug URL
              </label>
              <div className="flex">
                <span className="inline-flex items-center px-3 rounded-l-xl border border-r-0 border-border/50 bg-surface-elevated text-foreground-muted text-sm italic">
                  /blog/
                </span>
                <input
                  name="slug"
                  defaultValue={initialData?.slug}
                  placeholder="post-slug-here"
                  required
                  className="flex-1 px-4 py-2.5 bg-background border border-border/50 rounded-r-xl focus:ring-2 focus:ring-primary/20 focus:border-primary outline-none transition-all text-sm"
                />
              </div>
            </div>

            <div className="space-y-2">
              <label className="text-sm font-semibold text-foreground flex items-center gap-2">
                <FileText size={16} className="text-primary/60" />
                Content (Markdown supported)
              </label>
              <textarea
                name="content"
                defaultValue={initialData?.content}
                placeholder="Write your story here..."
                required
                rows={15}
                className="w-full px-4 py-3 bg-background border border-border/50 rounded-xl focus:ring-2 focus:ring-primary/20 focus:border-primary outline-none transition-all text-sm font-mono leading-relaxed"
              />
            </div>
          </div>
        </div>

        {/* Sidebar / Metadata */}
        <div className="space-y-6">
          {/* Status & Settings */}
          <div className="bg-surface border border-border/50 rounded-2xl p-6 space-y-6 card-shadow">
            <h3 className="text-sm font-bold uppercase tracking-widest text-foreground-muted">Publishing</h3>
            
            <div className="space-y-2">
              <label className="text-sm font-semibold text-foreground">Status</label>
              <select
                name="status"
                defaultValue={initialData?.status || BlogStatus.DRAFT}
                className="w-full px-4 py-2.5 bg-background border border-border/50 rounded-xl focus:ring-2 focus:ring-primary/20 focus:border-primary outline-none transition-all text-sm"
              >
                <option value={BlogStatus.DRAFT}>Draft</option>
                <option value={BlogStatus.PUBLISHED}>Published</option>
                <option value={BlogStatus.SCHEDULED}>Scheduled</option>
              </select>
            </div>

             <div className="space-y-2 pt-2 border-t border-border/50">
              <label className="text-sm font-semibold text-foreground flex items-center gap-2">
                <Layout size={16} className="text-primary/60" />
                Excerpt
              </label>
              <textarea
                name="excerpt"
                defaultValue={initialData?.excerpt}
                placeholder="Brief summary of the post..."
                rows={4}
                className="w-full px-4 py-3 bg-background border border-border/50 rounded-xl focus:ring-2 focus:ring-primary/20 focus:border-primary outline-none transition-all text-sm leading-snug"
              />
            </div>
          </div>

          {/* Tags */}
          <div className="bg-surface border border-border/50 rounded-2xl p-6 space-y-4 card-shadow">
            <h3 className="text-sm font-bold uppercase tracking-widest text-foreground-muted flex items-center gap-2">
              <TagIcon size={14} />
              Tags
            </h3>
            
            <div className="flex gap-2">
              <input
                value={tagInput}
                onChange={(e) => setTagInput(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && (e.preventDefault(), addTag())}
                placeholder="Add tag..."
                className="flex-1 px-3 py-2 bg-background border border-border/50 rounded-lg text-xs outline-none focus:border-primary"
              />
              <button
                type="button"
                onClick={addTag}
                className="p-2 bg-primary/10 text-primary rounded-lg hover:bg-primary/20 transition-colors"
              >
                <Plus size={16} />
              </button>
            </div>

            <div className="flex flex-wrap gap-2 pt-2">
              {tags.map((tag) => (
                <span
                  key={tag}
                  className="inline-flex items-center gap-1 px-2 py-1 bg-surface-elevated border border-border/50 rounded-md text-[10px] font-bold text-foreground"
                >
                  {tag}
                  <button
                    type="button"
                    onClick={() => removeTag(tag)}
                    className="p-0.5 hover:text-destructive transition-colors"
                  >
                    <X size={10} />
                  </button>
                </span>
              ))}
              {tags.length === 0 && (
                <p className="text-xs text-foreground-muted italic">No tags added yet.</p>
              )}
            </div>
          </div>
        </div>
      </div>
    </form>
  );
}
