"use client";

import { useEffect, useState } from "react";
import { useRouter, useParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { RichTextEditor } from "@/components/ui/rich-text-editor";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Loader2, ArrowLeft } from "lucide-react";
import { toast } from "sonner";
import api from "@/lib/api";
import Link from "next/link";
import { PageHeaderSkeleton } from "@/components/shared";
import type { Post, BlogCategory } from "@/lib/types";

export default function EditPostPage() {
  const router = useRouter();
  const params = useParams();
  const slug = params.slug as string;
  const [categories, setCategories] = useState<BlogCategory[]>([]);
  const [loading, setLoading] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [form, setForm] = useState({
    category_id: "",
    title: "",
    excerpt: "",
    content: "",
    status: "draft",
    is_featured: false,
    meta_title: "",
    meta_description: "",
    tags: "",
  });
  const [featuredImage, setFeaturedImage] = useState<File | null>(null);
  const [existingImage, setExistingImage] = useState<string | null>(null);

  useEffect(() => {
    Promise.all([
      api.get(`/api/posts/${slug}`),
      api.get("/api/posts/categories"),
    ]).then(([postRes, catRes]) => {
      const post: Post = postRes.data.data;
      setForm({
        category_id: post.category_id || post.category?.id || "",
        title: post.title,
        excerpt: post.excerpt || "",
        content: post.body || post.content || "",
        status: post.status,
        is_featured: post.is_featured || false,
        meta_title: post.meta_title || "",
        meta_description: post.meta_description || "",
        tags: post.tags?.map((t) => t.name).join(", ") || "",
      });
      setExistingImage(post.featured_image_thumbnail || null);
      setCategories(catRes.data.data);
      setLoading(false);
    }).catch(() => {
      toast.error("Failed to load post");
      router.push("/dashboard/blog");
    });
  }, [slug]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    try {
      const formData = new FormData();
      formData.append("_method", "PUT");
      Object.entries(form).forEach(([key, value]) => {
        if (key === "is_featured") {
          formData.append(key, value ? "1" : "0");
        } else if (key === "content") {
          formData.append("body", String(value));
        } else if (key === "tags") {
          if (value) {
            String(value).split(",").map(t => t.trim()).filter(Boolean).forEach((tag, i) => {
              formData.append(`tags[${i}]`, tag);
            });
          }
        } else if (value !== undefined && value !== null) {
          formData.append(key, String(value));
        }
      });
      if (featuredImage) formData.append("featured_image", featuredImage);

      await api.post(`/api/posts/${slug}`, formData, {
        headers: { "Content-Type": "multipart/form-data" },
      });
      toast.success("Post updated successfully");
      router.push("/dashboard/blog");
    } catch (err: any) {
      const message = err.response?.data?.message || "Failed to update post";
      toast.error(message);
    } finally {
      setIsSubmitting(false);
    }
  };

  if (loading) return <PageHeaderSkeleton />;

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="sm" asChild>
          <Link href="/dashboard/blog">
            <ArrowLeft className="mr-2 h-4 w-4" /> Back
          </Link>
        </Button>
        <div>
          <h1 className="font-display text-2xl font-semibold">Edit Post</h1>
          <p className="text-sm text-muted-foreground">Update blog post content</p>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        <div className="grid gap-6 lg:grid-cols-3">
          <Card className="lg:col-span-2">
            <CardHeader>
              <CardTitle className="text-base">Content</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="title">Title *</Label>
                <Input id="title" value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} required />
              </div>
              <div className="space-y-2">
                <Label htmlFor="excerpt">Excerpt</Label>
                <Textarea id="excerpt" value={form.excerpt} onChange={(e) => setForm({ ...form, excerpt: e.target.value })} rows={2} />
              </div>
              <div className="space-y-2">
                <Label htmlFor="content">Content *</Label>
                <RichTextEditor
                  content={form.content}
                  onChange={(html) => setForm({ ...form, content: html })}
                  placeholder="Write your post content here..."
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="tags">Tags</Label>
                <Input id="tags" value={form.tags} onChange={(e) => setForm({ ...form, tags: e.target.value })} placeholder="Comma-separated tags" />
              </div>
            </CardContent>
          </Card>

          <div className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle className="text-base">Publishing</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-2">
                  <Label>Category *</Label>
                  <Select value={form.category_id} onValueChange={(v) => setForm({ ...form, category_id: v })}>
                    <SelectTrigger><SelectValue placeholder="Select category" /></SelectTrigger>
                    <SelectContent>
                      {categories.map((cat) => (
                        <SelectItem key={cat.id} value={cat.id}>{cat.name}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label>Status</Label>
                  <Select value={form.status} onValueChange={(v) => setForm({ ...form, status: v })}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="draft">Draft</SelectItem>
                      <SelectItem value="published">Published</SelectItem>
                      <SelectItem value="archived">Archived</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="flex items-center justify-between">
                  <Label>Featured Post</Label>
                  <Switch checked={form.is_featured} onCheckedChange={(checked) => setForm({ ...form, is_featured: checked })} />
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-base">Featured Image</CardTitle>
              </CardHeader>
              <CardContent className="space-y-2">
                {featuredImage ? (
                  <img src={URL.createObjectURL(featuredImage)} alt="New preview" className="mb-2 h-32 w-full rounded-md object-cover" />
                ) : existingImage ? (
                  <img src={existingImage} alt="Featured" className="mb-2 h-32 w-full rounded-md object-cover" />
                ) : null}
                <Input type="file" accept="image/*" onChange={(e) => setFeaturedImage(e.target.files?.[0] || null)} />
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-base">SEO</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-2">
                  <Label>Meta Title</Label>
                  <Input value={form.meta_title} onChange={(e) => setForm({ ...form, meta_title: e.target.value })} maxLength={70} />
                  <p className="text-xs text-muted-foreground">{form.meta_title.length}/70</p>
                </div>
                <div className="space-y-2">
                  <Label>Meta Description</Label>
                  <Textarea value={form.meta_description} onChange={(e) => setForm({ ...form, meta_description: e.target.value })} maxLength={160} rows={3} />
                  <p className="text-xs text-muted-foreground">{form.meta_description.length}/160</p>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>

        <div className="flex justify-end gap-3">
          <Button variant="outline" asChild>
            <Link href="/dashboard/blog">Cancel</Link>
          </Button>
          <Button type="submit" disabled={isSubmitting}>
            {isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            Update Post
          </Button>
        </div>
      </form>
    </div>
  );
}
