import React, { useState, useEffect } from 'react';
import { Head, router } from '@inertiajs/react';
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
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 { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
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, Save, ImagePlus, ArrowLeft, X, Star, Trash2, Link as LinkIcon, Upload } from 'lucide-react';
import axios from 'axios';
import { toast } from 'sonner';
import useTranslation from '@/hooks/useTranslation';

import TiptapEditor from '@/components/TiptapEditor';

export default function EditPost({ auth, post }) {
    const { t } = useTranslation();

    // --- State ---
    const [data, setData] = useState({
        title: post.title || '',
        meta_description: post.meta_description || '',
        category_id: String(post.category_id || ''),
        content: post.content || '',
        tags: post.tags || [],
    });

    const [existingImages, setExistingImages] = useState(post.images || []);
    
    const [newImages, setNewImages] = useState(() => {
        if ((!post.images || post.images.length === 0) && post.image_path) {
            return [{
                type: 'url',
                file: null,
                url: post.image_path,
                preview: post.image_path,
                caption: '',
                isPrimary: true
            }];
        }
        return [];
    });

    const [deletedImageIds, setDeletedImageIds] = useState([]);

    // UI State
    const [activeTab, setActiveTab] = useState('upload');
    const [urlInput, setUrlInput] = useState('');
    const [categories, setCategories] = useState([]);
    const [tagInput, setTagInput] = useState("");
    const [isLoadingCategories, setIsLoadingCategories] = useState(true);
    const [isSubmitting, setIsSubmitting] = useState(false);

    useEffect(() => {
        axios.get('/api/user/categories')
            .then(res => {
                setCategories(res.data);
                setIsLoadingCategories(false);
            })
            .catch(() => {
                toast.error(t('_failed_load_categories', 'Failed to load categories.'));
                setIsLoadingCategories(false);
            });
    }, []);

    const handleImageSelect = (e) => {
        const files = Array.from(e.target.files);
        if (existingImages.length + newImages.length + files.length > 5) {
            toast.error(t('_max_images_allowed', 'Maximum 5 images allowed.'));
            return;
        }

        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 = '';
    };

    const handleUrlAdd = () => {
        if (!urlInput.trim()) return;
        try { new URL(urlInput); } catch (_) { toast.error(t('_invalid_url_error', 'Invalid URL')); return; }

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

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

    const deleteExistingImage = (id) => {
        const imgToDelete = existingImages.find(img => img.id === id);
        setDeletedImageIds([...deletedImageIds, id]);
        
        const updatedExisting = existingImages.filter(img => img.id !== id);
        setExistingImages(updatedExisting);

        if (imgToDelete.is_primary) {
            if (updatedExisting.length > 0) {
                updatedExisting[0].is_primary = 1;
                setExistingImages(updatedExisting);
            } else if (newImages.length > 0) {
                const updatedNew = [...newImages];
                updatedNew[0].isPrimary = true;
                setNewImages(updatedNew);
            }
        }
    };

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

        if (imgToDelete.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);
            }
        }
    };

    const setPrimary = (type, identifier) => {
        const updatedExisting = existingImages.map(img => ({ ...img, is_primary: 0 }));
        const updatedNew = newImages.map(img => ({ ...img, isPrimary: false }));

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

        setExistingImages(updatedExisting);
        setNewImages(updatedNew);
    };

    const updateExistingCaption = (id, text) => {
        setExistingImages(existingImages.map(img => img.id === id ? { ...img, caption: text } : img));
    };

    const updateNewCaption = (index, text) => {
        const updated = [...newImages];
        updated[index].caption = text;
        setNewImages(updated);
    };

    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(t('_max_tags_allowed', 'Max 5 tags.')); }
                setData({ ...data, tags: [...data.tags, newTag] });
                setTagInput("");
            }
        }
    };

    const removeTag = (tag) => {
        setData({ ...data, tags: data.tags.filter(t => t !== tag) });
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        
        if (!data.content || data.content === '<p></p>') {
            toast.error(t('_content_required', 'Content required.'));
            return;
        }

        if (existingImages.length + newImages.length === 0) {
            toast.error(t('_cover_image_required', 'At least one image is required.'));
            return;
        }

        setIsSubmitting(true);

        const formData = new FormData();
        formData.append('_method', 'PUT');
        formData.append('title', data.title);
        formData.append('meta_description', data.meta_description);
        formData.append('category_id', data.category_id);
        formData.append('content', data.content);
        formData.append('tags', JSON.stringify(data.tags));

        deletedImageIds.forEach(id => formData.append('deleted_image_ids[]', id));
        existingImages.forEach(img => {
            formData.append(`existing_captions[${img.id}]`, img.caption || '');
            if (img.is_primary) formData.append('primary_existing_id', img.id);
        });
        newImages.forEach((img, index) => {
            formData.append(`new_items[${index}][type]`, img.type);
            formData.append(`new_items[${index}][caption]`, img.caption || '');
            formData.append(`new_items[${index}][is_primary]`, img.isPrimary ? '1' : '0');

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

        try {
            await axios.post(`/api/user/my-posts/${post.id}`, formData, {
                headers: { 'Content-Type': 'multipart/form-data' }
            });
            toast.success(t('_post_updated_success', 'Post updated successfully!'));
            router.visit(route('my-posts.index'));
        } catch (error) {
            if (error.response?.data?.errors) {
                Object.values(error.response.data.errors).forEach(err => toast.error(err[0]));
            } else {
                toast.error(t('_update_failed', 'Update failed.'));
            }
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <AuthenticatedLayout user={auth.user} header={
            <div className="flex items-center gap-4">
                <Button variant="ghost" size="icon" onClick={() => window.history.back()}><ArrowLeft className="h-5 w-5 rtl:rotate-180" /></Button>
                <h2 className="font-semibold text-xl text-foreground">{t('_edit_post', 'Edit Post')}</h2>
            </div>
        }>
            <Head title={`${t('_edit', 'Edit')} - ${post.title}`} />

            <div className="py-12">
                <div className="max-w-4xl mx-auto sm:px-6 lg:px-8">
                    <Card className="shadow-lg">
                        <CardHeader>
                            <CardTitle>{t('_edit_details', 'Edit Details')}</CardTitle>
                            <CardDescription>{t('_edit_details_desc', 'Update your story. Changes will require re-approval.')}</CardDescription>
                        </CardHeader>
                        <CardContent>
                            <form onSubmit={handleSubmit} className="space-y-6">
                                
                                <div className="space-y-4">
                                    <div className="space-y-2">
                                        <Label>{t('_headline', 'Headline')}</Label>
                                        <Input value={data.title} onChange={e => setData({...data, title: e.target.value})} required />
                                    </div>
                                    <div className="space-y-2">
                                        <Label>{t('_short_description_seo', 'Short Description')} ({data.meta_description.length}/160)</Label>
                                        <Textarea value={data.meta_description} onChange={e => e.target.value.length <= 160 && setData({...data, meta_description: e.target.value})} className="h-20 resize-none" required />
                                    </div>
                                </div>

                                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                    <div className="space-y-2">
                                        <Label>{t('_category', 'Category')}</Label>
                                        <Select value={data.category_id} onValueChange={val => setData({...data, category_id: val})}>
                                            <SelectTrigger className="text-start"><SelectValue placeholder={t('_select_category', 'Select Category')} /></SelectTrigger>
                                            <SelectContent>
                                                {categories.map(p => (
                                                    <SelectGroup key={p.id}>
                                                        <SelectLabel className="text-primary text-start">{p.name}</SelectLabel>
                                                        <SelectItem value={String(p.id)} className="ps-6">{p.name} ({t('_main', 'Main')})</SelectItem>
                                                        {p.children?.map(c => <SelectItem key={c.id} value={String(c.id)} className="ps-8">↳ {c.name}</SelectItem>)}
                                                    </SelectGroup>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                    </div>
                                    <div className="space-y-2">
                                        <Label>{t('_tags', 'Tags')}</Label>
                                        <Input placeholder={t('_type_tag_enter', 'Type tag & Enter')} value={tagInput} onChange={e => setTagInput(e.target.value)} onKeyDown={handleTagKeyDown} />
                                        <div className="flex flex-wrap gap-2 mt-2">
                                            {data.tags.map((tag, i) => (
                                                <Badge key={i} variant="secondary" className="gap-1">{tag} <X className="w-3 h-3 cursor-pointer" onClick={() => removeTag(tag)} /></Badge>
                                            ))}
                                        </div>
                                    </div>
                                </div>

                                {/* --- IMAGES SECTION --- */}
                                <div className="border rounded-lg p-4 bg-muted/20 space-y-4">
                                    <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                                        <Label className="text-base">{t('_gallery', 'Gallery')} ({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">{t('_upload', 'Upload')}</TabsTrigger>
                                                <TabsTrigger value="url">{t('_direct_url', 'Direct URL')}</TabsTrigger>
                                            </TabsList>
                                        </Tabs>
                                    </div>

                                    <div className="flex gap-2 items-center">
                                        {activeTab === 'upload' ? (
                                            <>
                                                <input type="file" id="edit-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('edit-img-upload').click()} disabled={existingImages.length + newImages.length >= 5}>
                                                    <Upload className="w-4 h-4 me-2" /> {t('_browse_files', '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 me-2" /> {t('_add', 'Add')}
                                                </Button>
                                            </div>
                                        )}
                                    </div>

                                    <div className="space-y-3">
                                        {existingImages.map((img) => (
                                            <div key={img.id} className={`flex gap-4 p-3 rounded-md border bg-card ${img.is_primary ? 'border-primary ring-1 ring-primary' : ''}`}>
                                                <div className="relative w-24 h-24 shrink-0 bg-muted rounded-md overflow-hidden">
                                                    <img src={img.image_path} className="w-full h-full object-cover" alt="Stored" />
                                                    
                                                    {Boolean(img.is_primary) && (
                                                        <div className="absolute top-0 start-0 bg-primary text-primary-foreground text-[10px] px-1.5 py-0.5 rounded-ee font-semibold">
                                                            {t('_primary', 'Primary')}
                                                        </div>
                                                    )}
                                                </div>
                                                <div className="flex-1 space-y-2">
                                                    <Input placeholder={t('_optional_caption', 'Caption...')} value={img.caption || ''} onChange={e => updateExistingCaption(img.id, e.target.value)} className="h-8 text-sm" />
                                                    <div className="flex gap-3">
                                                        <Button type="button" variant={img.is_primary ? "default" : "secondary"} size="sm" className="h-7 text-xs" onClick={() => setPrimary('existing', img.id)}>
                                                            <Star className={`w-3 h-3 me-1 ${img.is_primary ? 'fill-current' : ''}`} /> 
                                                            {img.is_primary ? t('_primary', 'Primary') : t('_set_primary', 'Set Primary')}
                                                        </Button>
                                                        <Button type="button" variant="ghost" size="sm" className="h-7 text-xs text-red-500" onClick={() => deleteExistingImage(img.id)}>
                                                            <Trash2 className="w-3 h-3 me-1" /> {t('_remove', 'Remove')}
                                                        </Button>
                                                    </div>
                                                </div>
                                            </div>
                                        ))}

                                        {newImages.map((img, idx) => (
                                            <div key={idx} className={`flex gap-4 p-3 rounded-md border bg-card ${img.isPrimary ? 'border-primary ring-1 ring-primary' : ''}`}>
                                                <div className="relative w-24 h-24 shrink-0 bg-muted rounded-md overflow-hidden">
                                                    <img src={img.preview} className="w-full h-full object-cover" alt="New" />
                                                    
                                                    <div className="absolute top-0 end-0 bg-green-500 text-white text-[10px] px-1.5 py-0.5 rounded-es">New</div>
                                                    
                                                    {img.type === 'url' && <div className="absolute top-0 start-0 bg-black/50 text-white p-1 rounded-ee"><LinkIcon className="w-3 h-3"/></div>}
                                                    
                                                    {img.isPrimary && (
                                                        <div className="absolute bottom-0 start-0 bg-primary text-primary-foreground text-[10px] px-1.5 py-0.5 rounded-se font-semibold">
                                                            {t('_primary', 'Primary')}
                                                        </div>
                                                    )}
                                                </div>
                                                <div className="flex-1 space-y-2">
                                                    <Input placeholder={t('_optional_caption', 'Caption...')} value={img.caption} onChange={e => updateNewCaption(idx, e.target.value)} className="h-8 text-sm" />
                                                    <div className="flex gap-3">
                                                        <Button type="button" variant={img.isPrimary ? "default" : "secondary"} size="sm" className="h-7 text-xs" onClick={() => setPrimary('new', idx)}>
                                                            <Star className={`w-3 h-3 me-1 ${img.isPrimary ? 'fill-current' : ''}`} /> 
                                                            {img.isPrimary ? t('_primary', 'Primary') : t('_set_primary', 'Set Primary')}
                                                        </Button>
                                                        <Button type="button" variant="ghost" size="sm" className="h-7 text-xs text-red-500" onClick={() => deleteNewImage(idx)}>
                                                            <Trash2 className="w-3 h-3 me-1" /> {t('_remove', 'Remove')}
                                                        </Button>
                                                    </div>
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                </div>

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

                                <div className="flex justify-end pt-2">
                                    <Button type="submit" disabled={isSubmitting || isLoadingCategories}>
                                        <Loader2 className={`me-2 h-4 w-4 ${isSubmitting ? 'animate-spin' : 'hidden'}`} />
                                        <Save className={`me-2 h-4 w-4 ${isSubmitting ? 'hidden' : ''}`} />
                                        {isSubmitting ? t('_saving', 'Saving...') : t('_save_changes', 'Save Changes')}
                                    </Button>
                                </div>
                            </form>
                        </CardContent>
                    </Card>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}