"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { Blog } from "@/types/models";
import { Loader2, Pencil, X } from "lucide-react";
import Image from "next/image";

import { Button } from "@/components/ui/button";
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/hooks/use-toast";
import { updateBlog } from "../_actions/blog";
import { URL_IMAGE } from "@/utils/url";

export function ManageBlog({ blog }: { blog: Blog }) {
    const t = useTranslations();
    const { toast } = useToast();
    const [open, setOpen] = useState(false);
    const [loading, setLoading] = useState(false);
    const [preview, setPreview] = useState<string | null>(blog.image ? `${URL_IMAGE}/${blog.image}` : null);

    const handleSubmit = async (formData: FormData) => {
        setLoading(true);
        // Ensure _method is PATCH for compatibility if backend expects it
        formData.append("_method", "PATCH");
        
        try {
            const res = await updateBlog(blog.id, formData);
            if (res.success) {
                toast({
                    description: res.message,
                    className: "bg-green-500 text-white",
                });
                setOpen(false);
            } else {
                toast({
                    variant: "destructive",
                    description: res.message,
                });
            }
        } catch (error) {
             toast({
                variant: "destructive",
                description: t("custom.err"),
            });
        } finally {
            setLoading(false);
        }
    };

    const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (file) {
            const objectUrl = URL.createObjectURL(file);
            setPreview(objectUrl);
        }
    };

    return (
        <Dialog open={open} onOpenChange={setOpen}>
            <DialogTrigger asChild>
                <Button variant="ghost" size="icon" className="absolute top-1 left-2 bg-white/80 hover:bg-white shadow-sm z-10 rounded-full h-8 w-8">
                    <Pencil className="h-4 w-4 text-gray-700" />
                </Button>
            </DialogTrigger>
            <DialogContent className="sm:max-w-[500px]">
                <DialogHeader>
                    <DialogTitle>{t("actions.edit")} {t("single-word.blog") || "Blog"}</DialogTitle>
                    <DialogDescription>
                        {t("profile.edit_blog_desc") || "Make changes to your blog post here. Click save when you're done."}
                    </DialogDescription>
                </DialogHeader>
                
                <form action={handleSubmit} className="space-y-4 py-4">
                    <div className="space-y-2">
                        <Label htmlFor="image">{t("custom.image") || "Image"}</Label>
                        <div className="flex flex-col gap-4">
                            {preview && (
                                <div className="relative h-40 w-full rounded-md overflow-hidden bg-gray-100 border">
                                    <Image 
                                        src={preview} 
                                        alt="Preview" 
                                        fill 
                                        className="object-cover"
                                    />
                                    <Button 
                                        type="button"
                                        variant="destructive" 
                                        size="icon" 
                                        className="absolute top-2 right-2 h-6 w-6 rounded-full"
                                        onClick={() => {
                                            setPreview(null);
                                        }}
                                    >
                                        <X className="h-3 w-3" />
                                    </Button>
                                </div>
                            )}
                            <Input 
                                id="image" 
                                name="image" 
                                type="file" 
                                accept="image/*"
                                onChange={handleImageChange}
                                className="cursor-pointer"
                            />
                        </div>
                    </div>
                    
                    <div className="space-y-2">
                        <Label htmlFor="title">{t("custom.title") || "Title"}</Label>
                        <Input 
                            id="title" 
                            name="title" 
                            defaultValue={blog.title} 
                            placeholder={t("placeholder.title") || "Enter title..."}
                            required 
                        />
                    </div>
                    
                    <div className="space-y-2">
                        <Label htmlFor="content">{t("custom.content") || "Content"}</Label>
                        <Textarea 
                            id="content" 
                            name="content" 
                            defaultValue={blog.content?.replace(/<[^>]*>?/gm, "")} 
                            placeholder={t("placeholder.content") || "Write your content..."}
                            className="min-h-[150px]"
                            required 
                        />
                    </div>

                    <DialogFooter>
                        <Button type="button" variant="outline" onClick={() => setOpen(false)} disabled={loading}>
                            {t("custom.cancel")}
                        </Button>
                        <Button type="submit" disabled={loading}>
                            {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                            {t("custom.save")}
                        </Button>
                    </DialogFooter>
                </form>
            </DialogContent>
        </Dialog>
    );
}
