import React, { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Loader2, X, Save, Upload, Link as LinkIcon, Star, Trash2 } from 'lucide-react';
import TiptapEditor from '@/Components/TiptapEditor';
import axios from 'axios';
import { toast } from 'sonner';

export default function EditPostDialog({ open, onOpenChange, post, categories, onSuccess }) {
    // --- LOCAL STATE ---
    const [data, setData] = useState({
        title: '',
        meta_description: '',
        category_id: '',
        status: 'pending',
        content: '',
        tags: []
    });
    
    // Gallery State
    const [existingImages, setExistingImages] = useState([]);
    const [newImages, setNewImages] = useState([]); // { type, file, url, preview, caption, isPrimary }
    const [deletedImageIds, setDeletedImageIds] = useState([]);
    
    // UI State
    const [tagInput, setTagInput] = useState("");
    const [isSaving, setIsSaving] = useState(false);
    const [activeTab, setActiveTab] = useState('upload');
    const [urlInput, setUrlInput] = useState('');

    // --- INIT ---
    useEffect(() => {
        if (post) {
            setData({
                title: post.title || '',
                meta_description: post.meta_description || '',
                category_id: post.category_id ? String(post.category_id) : '',
                status: post.status || 'pending',
                content: post.content || '',
                tags: post.tags || []
            });
            setExistingImages(post.images || []);
            setDeletedImageIds([]);

            // RSS Fallback: If no gallery but has main image, load it as URL
            if ((!post.images || post.images.length === 0) && post.image_path) {
                setNewImages([{
                    type: 'url',
                    file: null,
                    url: post.image_path,
                    preview: post.image_path,
                    caption: '',
                    isPrimary: true
                }]);
            } else {
                setNewImages([]);
            }
        }
    }, [post]);

    // --- HANDLERS ---
    
    // 1. File Upload
    const handleImageSelect = (e) => {
        const files = Array.from(e.target.files);
        if (existingImages.length + newImages.length + files.length > 5) {
            return toast.error("Maximum 5 images allowed.");
        }
        const added = files.map(file => ({
            type: 'file',
            file: file,
            url: null,
            preview: URL.createObjectURL(file),
            caption: '',
            isPrimary: (existingImages.length === 0 && newImages.length === 0)
        }));
        setNewImages([...newImages, ...added]);
        e.target.value = '';
    };

    // 2. Direct URL
    const handleUrlAdd = () => {
        if (!urlInput.trim()) return;
        try { new URL(urlInput); } catch (_) { return toast.error("Invalid URL"); }

        if (existingImages.length + newImages.length >= 5) {
            return toast.error("Maximum 5 images allowed.");
        }

        setNewImages([...newImages, {
            type: 'url',
            file: null,
            url: urlInput,
            preview: urlInput,
            caption: '',
            isPrimary: (existingImages.length === 0 && newImages.length === 0)
        }]);
        setUrlInput('');
        toast.success("URL Added");
    };

    // Deletion
    const deleteExisting = (id) => {
        const img = existingImages.find(i => i.id === id);
        setDeletedImageIds([...deletedImageIds, id]);
        const updatedExisting = existingImages.filter(i => i.id !== id);
        setExistingImages(updatedExisting);

        // Reassign primary
        if (img.is_primary) {
            if (updatedExisting.length > 0) updatedExisting[0].is_primary = 1;
            else if (newImages.length > 0) {
                const updatedNew = [...newImages];
                updatedNew[0].isPrimary = true;
                setNewImages(updatedNew);
            }
        }
    };

    const deleteNew = (index) => {
        const img = newImages[index];
        const updatedNew = newImages.filter((_, i) => i !== index);
        setNewImages(updatedNew);

        // Reassign primary
        if (img.isPrimary) {
            if (existingImages.length > 0) {
                const updatedExisting = [...existingImages];
                updatedExisting[0].is_primary = 1;
                setExistingImages(updatedExisting);
            } else if (updatedNew.length > 0) {
                updatedNew[0].isPrimary = true;
                setNewImages(updatedNew);
            }
        }
    };

    // Primary & Caption
    const setPrimary = (type, identifier) => {
        const upEx = existingImages.map(img => ({ ...img, is_primary: 0 }));
        const upNew = newImages.map(img => ({ ...img, isPrimary: false }));

        if (type === 'existing') {
            const target = upEx.find(img => img.id === identifier);
            if (target) target.is_primary = 1;
        } else {
            if (upNew[identifier]) upNew[identifier].isPrimary = true;
        }
        setExistingImages(upEx);
        setNewImages(upNew);
    };

    const updateCaption = (type, identifier, val) => {
        if (type === 'existing') {
            setExistingImages(prev => prev.map(img => img.id === identifier ? { ...img, caption: val } : img));
        } else {
            setNewImages(prev => prev.map((img, i) => i === identifier ? { ...img, caption: val } : img));
        }
    };

    // Tags
    const handleTagKeyDown = (e) => {
        if (e.key === 'Enter' || e.key === ',') {
            e.preventDefault();
            const newTag = tagInput.trim();
            if (newTag && !data.tags.includes(newTag)) {
                if (data.tags.length >= 5) return toast.error("Max 5 tags.");
                setData(prev => ({ ...prev, tags: [...prev.tags, newTag] }));
                setTagInput("");
            }
        }
    };

    // Save
    const handleSubmit = async (e) => {
        e.preventDefault();
        if (existingImages.length + newImages.length === 0) return toast.error("Image required.");
        
        setIsSaving(true);
        const formData = new FormData();
        formData.append('_method', 'PUT');
        Object.keys(data).forEach(key => {
            if (key === 'tags') formData.append(key, JSON.stringify(data[key]));
            else formData.append(key, data[key]);
        });

        deletedImageIds.forEach(id => formData.append('deleted_image_ids[]', id));
        
        // Existing
        existingImages.forEach(img => {
            formData.append(`existing_captions[${img.id}]`, img.caption || '');
            if (img.is_primary) formData.append('primary_existing_id', img.id);
        });

        // New Items (Files & URLs)
        newImages.forEach((img, index) => {
            formData.append(`items[${index}][type]`, img.type);
            formData.append(`items[${index}][caption]`, img.caption || '');
            formData.append(`items[${index}][is_primary]`, img.isPrimary ? '1' : '0');

            if (img.type === 'file') {
                formData.append(`items[${index}][file]`, img.file);
            } else {
                formData.append(`items[${index}][url]`, img.url);
            }
        });

        try {
            await axios.post(`/api/admin/posts/${post.id}`, formData, { headers: { 'Content-Type': 'multipart/form-data' } });
            toast.success("Post saved!");
            onSuccess();
            onOpenChange(false);
        } catch (error) {
            toast.error(error.response?.data?.message || "Save failed.");
        } finally {
            setIsSaving(false);
        }
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto flex flex-col">
                <DialogHeader>
                    <DialogTitle>Edit Post</DialogTitle>
                    <DialogDescription>Modify content, status, and gallery.</DialogDescription>
                </DialogHeader>

                <form onSubmit={handleSubmit} className="space-y-5 py-4 flex-1">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <div className="space-y-2 md:col-span-2">
                            <Label>Headline</Label>
                            <Input value={data.title} onChange={e => setData({...data, title: e.target.value})} required />
                        </div>
                        
                        <div className="space-y-2 md:col-span-2">
                            <Label>SEO Description</Label>
                            <Textarea value={data.meta_description} onChange={e => setData({...data, meta_description: e.target.value})} className="h-20 resize-none" />
                        </div>

                        <div className="space-y-2">
                            <Label>Category</Label>
                            <Select value={data.category_id} onValueChange={val => setData({...data, category_id: val})}>
                                <SelectTrigger><SelectValue placeholder="Select Category" /></SelectTrigger>
                                <SelectContent>
                                    {categories.map(parent => (
                                        <SelectGroup key={parent.id}>
                                            <SelectLabel>{parent.name}</SelectLabel>
                                            <SelectItem value={String(parent.id)}>{parent.name} (Main)</SelectItem>
                                            {parent.children?.map(child => <SelectItem key={child.id} value={String(child.id)} className="pl-6">↳ {child.name}</SelectItem>)}
                                        </SelectGroup>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>

                        <div className="space-y-2">
                            <Label>Status</Label>
                            <Select value={data.status} onValueChange={val => setData({...data, status: val})}>
                                <SelectTrigger><SelectValue /></SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="pending">Pending Review</SelectItem>
                                    <SelectItem value="published">Published</SelectItem>
                                    <SelectItem value="rejected">Rejected</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>

                        <div className="space-y-2 md:col-span-2">
                            <Label>Tags</Label>
                            <div className="flex flex-wrap gap-2 mb-2 p-2 border rounded-md min-h-[42px] items-center bg-background">
                                {data.tags.map(tag => (
                                    <Badge key={tag} variant="secondary" className="gap-1 pl-2.5">
                                        {tag} <X className="w-3 h-3 cursor-pointer" onClick={() => setData(prev => ({...prev, tags: prev.tags.filter(t => t !== tag)}))} />
                                    </Badge>
                                ))}
                                <input 
                                    className="flex-1 bg-transparent outline-none text-sm min-w-[100px]" 
                                    placeholder="Type & Enter..." 
                                    value={tagInput}
                                    onChange={e => setTagInput(e.target.value)}
                                    onKeyDown={handleTagKeyDown}
                                />
                            </div>
                        </div>
                    </div>

                    {/* --- GALLERY SECTION --- */}
                    <div className="border rounded-lg p-4 bg-muted/10 space-y-4">
                        <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                            <Label className="text-base font-semibold">Gallery & Covers ({existingImages.length + newImages.length}/5)</Label>
                            
                            <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full sm:w-auto">
                                <TabsList className="grid w-full grid-cols-2">
                                    <TabsTrigger value="upload">Upload</TabsTrigger>
                                    <TabsTrigger value="url">Direct URL</TabsTrigger>
                                </TabsList>
                            </Tabs>
                        </div>

                        {/* Controls */}
                        <div className="flex gap-2 items-center">
                            {activeTab === 'upload' ? (
                                <>
                                    <input type="file" id="admin-img-upload" className="hidden" multiple accept="image/*" onChange={handleImageSelect} disabled={existingImages.length + newImages.length >= 5} />
                                    <Button type="button" variant="secondary" className="w-full sm:w-auto" onClick={() => document.getElementById('admin-img-upload').click()} disabled={existingImages.length + newImages.length >= 5}>
                                        <Upload className="w-4 h-4 mr-2" /> Browse Files
                                    </Button>
                                </>
                            ) : (
                                <div className="flex w-full gap-2">
                                    <Input placeholder="https://..." value={urlInput} onChange={e => setUrlInput(e.target.value)} className="bg-background" />
                                    <Button type="button" variant="secondary" onClick={handleUrlAdd} disabled={existingImages.length + newImages.length >= 5}>
                                        <LinkIcon className="w-4 h-4 mr-2" /> Add
                                    </Button>
                                </div>
                            )}
                        </div>

                        {/* Image List */}
                        <div className="space-y-3">
                            {(existingImages.length + newImages.length === 0) && (
                                <div className="text-center py-6 text-muted-foreground text-sm border-2 border-dashed rounded-md bg-background">
                                    No images uploaded. Add images to set a cover.
                                </div>
                            )}

                            {/* Existing Images */}
                            {existingImages.map(img => (
                                <GalleryItem 
                                    key={`existing-${img.id}`}
                                    src={img.image_path}
                                    caption={img.caption || ''}
                                    isPrimary={img.is_primary}
                                    type="existing"
                                    onCaptionChange={(val) => updateCaption('existing', img.id, val)}
                                    onSetPrimary={() => setPrimary('existing', img.id)}
                                    onDelete={() => deleteExisting(img.id)}
                                />
                            ))}

                            {/* New Images */}
                            {newImages.map((img, i) => (
                                <GalleryItem 
                                    key={`new-${i}`}
                                    src={img.preview}
                                    caption={img.caption}
                                    isPrimary={img.isPrimary}
                                    isNew={true}
                                    isUrl={img.type === 'url'}
                                    type="new"
                                    onCaptionChange={(val) => updateCaption('new', i, val)}
                                    onSetPrimary={() => setPrimary('new', i)}
                                    onDelete={() => deleteNew(i)}
                                />
                            ))}
                        </div>
                    </div>

                    <div className="space-y-2">
                        <Label>Content Body</Label>
                        <TiptapEditor 
                            content={data.content} 
                            onChange={html => setData({...data, content: html})}
                            uploadUrl="/api/admin/editor/image-upload"
                        />
                    </div>

                    <DialogFooter className="sticky bottom-0 bg-background pt-4 border-t">
                        <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
                        <Button type="submit" disabled={isSaving}>
                            {isSaving ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Save className="h-4 w-4 mr-2" />}
                            Save Changes
                        </Button>
                    </DialogFooter>
                </form>
            </DialogContent>
        </Dialog>
    );
}

// Sub-component for individual row
function GalleryItem({ src, caption, isPrimary, isNew, isUrl, onCaptionChange, onSetPrimary, onDelete }) {
    return (
        <div className={`flex gap-3 p-2 border bg-card rounded-md items-center transition-all ${isPrimary ? 'border-primary ring-1 ring-primary/20 bg-primary/5' : ''}`}>
            <div className="relative w-16 h-16 shrink-0 rounded overflow-hidden bg-muted border">
                <img src={src} className="w-full h-full object-cover" />
                {isNew && <span className="absolute top-0 right-0 bg-green-500 text-[8px] text-white px-1 font-bold">NEW</span>}
                {isUrl && <div className="absolute top-0 left-0 bg-black/50 text-white p-0.5 rounded-br"><LinkIcon className="w-2 h-2"/></div>}
            </div>
            
            <div className="flex-1 min-w-0">
                <Input 
                    value={caption} 
                    onChange={e => onCaptionChange(e.target.value)} 
                    placeholder="Enter image caption..." 
                    className="h-8 text-xs bg-background" 
                />
            </div>

            <div className="flex gap-1">
                <Button 
                    type="button" 
                    size="icon" 
                    variant={isPrimary ? 'default' : 'ghost'} 
                    onClick={onSetPrimary}
                    title="Set as Primary Cover"
                    className="h-8 w-8"
                >
                    <Star className={`w-4 h-4 ${isPrimary ? 'fill-current' : ''}`} />
                </Button>
                <Button 
                    type="button" 
                    size="icon" 
                    variant="ghost" 
                    className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10" 
                    onClick={onDelete}
                    title="Remove Image"
                >
                    <Trash2 className="w-4 h-4" />
                </Button>
            </div>
        </div>
    );
}