import React, { useState, useEffect } from 'react';
import { Head, useForm, router, usePage } 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 } from "@/components/ui/tabs";
import { CheckCircle2, Loader2, 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';

// Import our new sub-component
import QuickFetchCard from './Partials/QuickFetchCard';

export default function SubmitNews({ auth }) {
    const { t } = useTranslation(); 
    
    // --- 1. SETTINGS & PERMISSIONS ---
    const { post_settings } = usePage().props;
    const canQuickFetch = post_settings?.quick_fetch_enabled !== 'false' || auth.user.role === 'admin';

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

    const { data, setData } = useForm({
        title: '',
        meta_description: '',
        category_id: '',
        content: '',
        tags: [],
    });

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

    // --- HANDLE QUICK FETCH SUCCESS ---
    const handleFetchSuccess = (fetchedData) => {
        // Generate a quick meta description if missing
        const strippedContent = fetchedData.content ? fetchedData.content.replace(/<[^>]*>?/gm, '') : '';
        const tempMeta = strippedContent.substring(0, 155);

        // Update form data with fetched content
        setData(prevData => ({
            ...prevData,
            title: fetchedData.title || prevData.title,
            content: fetchedData.content || prevData.content,
            meta_description: prevData.meta_description || tempMeta
        }));

        // Handle Image Auto-attachment
        if (fetchedData.image && images.length < 5) {
            setImages(prevImages => {
                // Check if already attached to avoid duplicates
                if(prevImages.some(i => i.url === fetchedData.image)) return prevImages;
                
                // Construct the new dynamic caption (e.g., "Source: bbc.com")
                const dynamicCaption = `${t('_source', 'Source')}: ${fetchedData.source_domain || 'External'}`;

                return [
                    ...prevImages,
                    {
                        type: 'url',
                        file: null,
                        url: fetchedData.image,
                        preview: fetchedData.image,
                        caption: dynamicCaption, 
                        isPrimary: prevImages.length === 0
                    }
                ];
            });
        }
    };

    // --- Image Handlers ---

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

        const newItems = files.map((file, index) => ({
            type: 'file',
            file: file,
            url: null,
            preview: URL.createObjectURL(file),
            caption: '',
            isPrimary: images.length === 0 && index === 0
        }));

        setImages([...images, ...newItems]);
        e.target.value = ''; 
    };

    // 2. Handle URL Addition
    const handleUrlAdd = () => {
        if (!urlInput.trim()) return;
        
        try {
            new URL(urlInput);
        } catch (_) {
            toast.error(t('_invalid_url_error', 'Please enter a valid URL (e.g., https://example.com/image.jpg)'));
            return;
        }

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

        const newItem = {
            type: 'url',
            file: null,
            url: urlInput,
            preview: urlInput,
            caption: '',
            isPrimary: images.length === 0
        };

        setImages([...images, newItem]);
        setUrlInput('');
        toast.success(t('_image_url_added', 'Image URL added.'));
    };

    const removeImage = (index) => {
        const updatedImages = images.filter((_, i) => i !== index);
        // If primary was removed, assign primary to first available
        if (images[index].isPrimary && updatedImages.length > 0) {
            updatedImages[0].isPrimary = true;
        }
        setImages(updatedImages);
    };

    const setPrimaryImage = (index) => {
        const updatedImages = images.map((img, i) => ({
            ...img,
            isPrimary: i === index
        }));
        setImages(updatedImages);
    };

    const updateCaption = (index, text) => {
        const updatedImages = [...images];
        updatedImages[index].caption = text;
        setImages(updatedImages);
    };

    // --- Tag Handlers ---
    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) {
                    toast.error(t('_max_tags_allowed', 'Max 5 tags allowed.'));
                    return;
                }
                setData('tags', [...data.tags, newTag]);
                setTagInput("");
            }
        }
    };

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

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

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

        setIsSubmitting(true);

        const formData = new FormData();
        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));

        // Append Mixed Items
        images.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/user/posts', formData, {
                headers: { 'Content-Type': 'multipart/form-data' }
            });

            toast.success(t('_news_submitted_success', 'News submitted successfully!'));
            router.visit(route('my-posts.index'));
        } catch (error) {
            if (error.response && error.response.data.errors) {
                const errs = error.response.data.errors;
                Object.keys(errs).forEach(key => {
                    toast.error(errs[key][0]);
                });
            } else {
                toast.error(t('_submission_failed', 'Submission failed. Please check your inputs.'));
            }
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <AuthenticatedLayout user={auth.user}>
            <Head title={t('_submit_news', 'Submit News')} />

            <div className="py-12">
                <div className="max-w-4xl mx-auto sm:px-6 lg:px-8">
                    
                    {/* --- QUICK FETCH SUBCOMPONENT --- */}
                    {canQuickFetch && (
                        <QuickFetchCard onFetchSuccess={handleFetchSuccess} />
                    )}

                    {/* MAIN SUBMISSION CARD */}
                    <Card className="shadow-lg">
                        <CardHeader>
                            <CardTitle>{t('_create_post', 'Create Post')}</CardTitle>
                            <CardDescription>
                                {t('_share_story_desc', 'Share your story with the world.')}
                            </CardDescription>
                        </CardHeader>
                        <CardContent>
                            <form onSubmit={handleSubmit} className="space-y-6">
                                
                                {/* Title & Meta Description */}
                                <div className="space-y-4">
                                    <div className="space-y-2">
                                        <Label>{t('_headline', 'Headline')}</Label>
                                        <Input 
                                            value={data.title}
                                            onChange={(e) => setData('title', e.target.value)}
                                            placeholder={t('_enter_headline', 'Enter headline...')}
                                            required
                                        />
                                    </div>
                                    <div className="space-y-2">
                                        <div className="flex justify-between">
                                            <Label>{t('_short_description_seo', 'Short Description (SEO)')}</Label>
                                            <span className="text-xs text-muted-foreground">{data.meta_description.length}/160</span>
                                        </div>
                                        <Textarea 
                                            value={data.meta_description}
                                            onChange={(e) => {
                                                if (e.target.value.length <= 160) setData('meta_description', e.target.value);
                                            }}
                                            className="resize-none h-20"
                                            required
                                        />
                                    </div>
                                </div>

                                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                    {/* Category */}
                                    <div className="space-y-2">
                                        <Label>{t('_category', 'Category')}</Label>
                                        <Select onValueChange={(val) => setData('category_id', val)} value={data.category_id}>
                                            <SelectTrigger className="text-start"><SelectValue placeholder={t('_select_category', 'Select Category')} /></SelectTrigger>
                                            <SelectContent>
                                                {categories.map((parent) => (
                                                    <SelectGroup key={parent.id}>
                                                        <SelectLabel className="font-bold text-primary text-start">{parent.name}</SelectLabel>
                                                        <SelectItem value={String(parent.id)} className="ps-4">{parent.name} ({t('_main', 'Main')})</SelectItem>
                                                        {parent.children?.map((child) => (
                                                            <SelectItem key={child.id} value={String(child.id)} className="ps-8">↳ {child.name}</SelectItem>
                                                        ))}
                                                    </SelectGroup>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                    </div>

                                    {/* Tags */}
                                    <div className="space-y-2">
                                        <Label>{t('_tags', 'Tags')}</Label>
                                        <Input 
                                            placeholder={t('_type_tag_enter', 'Type tag & press 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>

                                {/* --- IMAGE UPLOAD SECTION --- */}
                                <div className="space-y-4 border rounded-lg p-4 bg-muted/20">
                                    <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                                        <Label className="text-base">{t('_cover_images', 'Cover Images')} ({images.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>

                                    {/* Tab Content */}
                                    <div className="flex gap-2 items-center">
                                        {activeTab === 'upload' ? (
                                            <>
                                                <input 
                                                    type="file" 
                                                    id="image-upload" 
                                                    className="hidden" 
                                                    multiple 
                                                    accept="image/*"
                                                    onChange={handleImageSelect}
                                                    disabled={images.length >= 5}
                                                />
                                                <Button 
                                                    type="button" 
                                                    variant="secondary" 
                                                    className="w-full sm:w-auto"
                                                    disabled={images.length >= 5}
                                                    onClick={() => document.getElementById('image-upload').click()}
                                                >
                                                    <Upload className="w-4 h-4 me-2" /> {t('_browse_files', 'Browse Files')}
                                                </Button>
                                            </>
                                        ) : (
                                            <div className="flex w-full gap-2">
                                                <Input 
                                                    placeholder="https://example.com/image.jpg" 
                                                    value={urlInput}
                                                    onChange={(e) => setUrlInput(e.target.value)}
                                                    className="bg-background"
                                                />
                                                <Button type="button" variant="secondary" onClick={handleUrlAdd} disabled={images.length >= 5}>
                                                    <LinkIcon className="w-4 h-4 me-2" /> {t('_add', 'Add')}
                                                </Button>
                                            </div>
                                        )}
                                    </div>

                                    {/* Image List */}
                                    <div className="space-y-3">
                                        {images.length === 0 && (
                                            <div className="text-center py-8 text-muted-foreground border-2 border-dashed rounded-md">
                                                {t('_no_images_selected', 'No images selected. Add at least one cover image.')}
                                            </div>
                                        )}
                                        {images.map((img, index) => (
                                            <div key={index} 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 border">
                                                    <img src={img.preview} className="w-full h-full object-cover" alt="Preview" />
                                                    {img.type === 'url' && (
                                                        <div className="absolute top-0 end-0 bg-black/50 text-white p-1 rounded-es">
                                                            <LinkIcon className="w-3 h-3" />
                                                        </div>
                                                    )}
                                                    {img.isPrimary && (
                                                        <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('_main_cover', 'Main Cover')}
                                                        </div>
                                                    )}
                                                </div>

                                                <div className="flex-1 space-y-2">
                                                    <Input 
                                                        placeholder={t('_optional_caption', 'Optional caption...')} 
                                                        value={img.caption}
                                                        onChange={(e) => updateCaption(index, e.target.value)}
                                                        className="h-8 text-sm"
                                                    />
                                                    <div className="flex items-center gap-3">
                                                        <Button 
                                                            type="button" 
                                                            variant={img.isPrimary ? "default" : "secondary"} 
                                                            size="sm" 
                                                            className="h-7 text-xs"
                                                            onClick={() => setPrimaryImage(index)}
                                                        >
                                                            <Star className={`w-3 h-3 me-1 ${img.isPrimary ? 'fill-current' : ''}`} />
                                                            {img.isPrimary ? t('_primary_cover', 'Primary Cover') : t('_set_as_primary', 'Set as Primary')}
                                                        </Button>
                                                        <Button 
                                                            type="button" 
                                                            variant="ghost" 
                                                            size="sm" 
                                                            className="h-7 text-xs text-red-500 hover:text-red-700 hover:bg-red-50"
                                                            onClick={() => removeImage(index)}
                                                        >
                                                            <Trash2 className="w-3 h-3 me-1" /> {t('_remove', 'Remove')}
                                                        </Button>
                                                    </div>
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                </div>

                                {/* Content Editor */}
                                <div className="space-y-2">
                                    <Label>{t('_story_content', 'Story Content')}</Label>
                                    <TiptapEditor 
                                        content={data.content} 
                                        onChange={(html) => setData('content', html)} 
                                    />
                                </div>

                                <div className="flex justify-end pt-2">
                                    <Button type="submit" disabled={isSubmitting || isLoadingCategories}>
                                        {isSubmitting ? <Loader2 className="me-2 h-4 w-4 animate-spin" /> : <CheckCircle2 className="me-2 h-4 w-4" />}
                                        {isSubmitting ? t('_submitting', 'Submitting...') : t('_submit_post', 'Submit Post')}
                                    </Button>
                                </div>
                            </form>
                        </CardContent>
                    </Card>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}