import React, { useState, useEffect } from 'react';
import { Head } from '@inertiajs/react';
import axios from 'axios';
import { toast } from 'sonner';
import AdminLayout from '@/Admin/Layouts/AdminLayout';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
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 { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from "@/components/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { PlusCircle, Pencil, Trash2, Code, Image as ImageIcon, Loader2 } from 'lucide-react';
import ConfirmModal from '@/Components/ConfirmModal'; 

const PREDEFINED_LOCATIONS = [
    { key: 'home_hero_top', label: 'Home: Above Hero (Leaderboard)' },
    { key: 'home_sidebar_top', label: 'Home: Sidebar Top (Square)' },
    { key: 'home_feed_middle', label: 'Home: Between News Feed' },
    { key: 'article_sidebar_top', label: 'Article: Sidebar Top' },
    { key: 'article_content_middle', label: 'Article: Inside Content' },
    { key: 'footer_top', label: 'Global: Above Footer' },
];

export default function AdManager() {
    const [ads, setAds] = useState([]);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isSaving, setIsSaving] = useState(false);
    const [editingAd, setEditingAd] = useState(null);

    const [deleteId, setDeleteId] = useState(null);
    const [isDeleteOpen, setIsDeleteOpen] = useState(false);

    const [formData, setFormData] = useState({
        name: '',
        placement_key: '',
        type: 'code',
        dimensions: '',
        target_url: '',
        content: '',
        image_file: null,
        is_active: true
    });

    useEffect(() => {
        fetchAds();
    }, []);

    const fetchAds = async () => {
        try {
            const res = await axios.get('/api/admin/ads');
            setAds(res.data);
        } catch (error) {
            toast.error("Failed to load ads");
        } finally {
            setLoading(false);
        }
    };

    const openModal = (ad = null) => {
        if (ad) {
            setEditingAd(ad);
            setFormData({
                name: ad.name,
                placement_key: ad.placement_key,
                type: ad.type,
                dimensions: ad.dimensions || '',
                target_url: ad.target_url || '',
                content: ad.type === 'code' ? (ad.content || '') : '',
                image_file: null,
                is_active: !!ad.is_active
            });
        } else {
            setEditingAd(null);
            setFormData({
                name: '',
                placement_key: '',
                type: 'code',
                dimensions: '',
                target_url: '',
                content: '',
                image_file: null,
                is_active: true
            });
        }
        setIsModalOpen(true);
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setIsSaving(true);

        const data = new FormData();
        data.append('name', formData.name);
        data.append('placement_key', formData.placement_key);
        data.append('type', formData.type);
        data.append('dimensions', formData.dimensions);
        data.append('target_url', formData.target_url || '');
        data.append('is_active', formData.is_active ? '1' : '0');

        if (formData.type === 'code') {
            data.append('code_content', formData.content);
        } else if (formData.image_file) {
            data.append('image_file', formData.image_file);
        }

        if (editingAd) {
            data.append('_method', 'PUT');
        }

        try {
            if (editingAd) {
                await axios.post(`/api/admin/ads/${editingAd.id}`, data, {
                    headers: { 'Content-Type': 'multipart/form-data' }
                });
                toast.success("Ad updated successfully");
            } else {
                await axios.post('/api/admin/ads', data, {
                    headers: { 'Content-Type': 'multipart/form-data' }
                });
                toast.success("Ad created successfully");
            }
            setIsModalOpen(false);
            fetchAds();
        } catch (error) {
            toast.error("Operation failed. Check inputs.");
            console.error(error);
        } finally {
            setIsSaving(false);
        }
    };

    const confirmDelete = (id) => {
        setDeleteId(id);
        setIsDeleteOpen(true);
    };

    const handleDelete = async () => {
        if (!deleteId) return;
        try {
            await axios.delete(`/api/admin/ads/${deleteId}`);
            setAds(ads.filter(a => a.id !== deleteId));
            toast.success("Ad deleted");
        } catch (error) {
            toast.error("Failed to delete");
        } finally {
            setIsDeleteOpen(false);
            setDeleteId(null);
        }
    };

    return (
        <AdminLayout header="Ad Placements">
            <Head title="Ad Manager" />

            <ConfirmModal 
                open={isDeleteOpen}
                onOpenChange={setIsDeleteOpen}
                onConfirm={handleDelete}
                title="Delete Ad Placement"
                description="Are you sure you want to delete this ad placement? This action cannot be undone."
                confirmText="Delete Ad"
                variant="destructive"
            />

            <div className="flex justify-between items-center mb-6">
                <div>
                    <h2 className="text-3xl font-bold tracking-tight">Ad Placements</h2>
                    <p className="text-muted-foreground">Manage advertisement slots and codes.</p>
                </div>
                <Button onClick={() => openModal()}>
                    <PlusCircle className="mr-2 h-4 w-4" /> New Placement
                </Button>
            </div>

            <Card>
                <CardHeader><CardTitle>Active Placements</CardTitle></CardHeader>
                <CardContent>
                    <Table>
                        <TableHeader>
                            <TableRow>
                                <TableHead>Placement Name</TableHead>
                                <TableHead>Key (Location)</TableHead>
                                <TableHead>Type</TableHead>
                                <TableHead>Size</TableHead>
                                <TableHead>Status</TableHead>
                                <TableHead className="text-right">Actions</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {loading ? (
                                <TableRow><TableCell colSpan={6} className="h-24 text-center">Loading...</TableCell></TableRow>
                            ) : ads.length === 0 ? (
                                <TableRow><TableCell colSpan={6} className="h-24 text-center">No ads configured.</TableCell></TableRow>
                            ) : (
                                ads.map((ad) => (
                                    <TableRow key={ad.id}>
                                        <TableCell className="font-medium">{ad.name}</TableCell>
                                        <TableCell>
                                            <Badge variant="outline" className="font-mono">{ad.placement_key}</Badge>
                                        </TableCell>
                                        <TableCell>
                                            <div className="flex items-center gap-2">
                                                {ad.type === 'code' ? <Code className="h-4 w-4 text-blue-500" /> : <ImageIcon className="h-4 w-4 text-green-500" />}
                                                <span className="capitalize">{ad.type}</span>
                                            </div>
                                        </TableCell>
                                        <TableCell>{ad.dimensions || 'Responsive'}</TableCell>
                                        <TableCell>
                                            <Badge variant={ad.is_active ? "default" : "secondary"}>
                                                {ad.is_active ? "Active" : "Inactive"}
                                            </Badge>
                                        </TableCell>
                                        <TableCell className="text-right space-x-2">
                                            <Button variant="ghost" size="icon" onClick={() => openModal(ad)}>
                                                <Pencil className="h-4 w-4" />
                                            </Button>
                                            <Button variant="ghost" size="icon" className="text-red-500" onClick={() => confirmDelete(ad.id)}>
                                                <Trash2 className="h-4 w-4" />
                                            </Button>
                                        </TableCell>
                                    </TableRow>
                                ))
                            )}
                        </TableBody>
                    </Table>
                </CardContent>
            </Card>

            <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
                <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
                    <DialogHeader>
                        <DialogTitle>{editingAd ? 'Edit Placement' : 'New Ad Placement'}</DialogTitle>
                        <DialogDescription>Configure where and how an ad appears.</DialogDescription>
                    </DialogHeader>

                    <form onSubmit={handleSubmit} className="space-y-4 py-2">
                        <div className="grid grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label>Placement Name</Label>
                                <Input 
                                    placeholder="e.g. Home Sidebar Top" 
                                    value={formData.name}
                                    onChange={(e) => setFormData({...formData, name: e.target.value})}
                                    required
                                />
                            </div>
                            <div className="space-y-2">
                                <Label>Dimensions</Label>
                                <Input 
                                    placeholder="e.g. 300x250 or Responsive" 
                                    value={formData.dimensions}
                                    onChange={(e) => setFormData({...formData, dimensions: e.target.value})}
                                />
                            </div>
                        </div>

                        <div className="space-y-2">
                            <Label>Location Key (Where to show)</Label>
                            <Select 
                                value={formData.placement_key} 
                                onValueChange={(val) => setFormData({...formData, placement_key: val})}
                                disabled={!!editingAd}
                            >
                                <SelectTrigger>
                                    <SelectValue placeholder="Select or type a location" />
                                </SelectTrigger>
                                <SelectContent>
                                    {PREDEFINED_LOCATIONS.map(loc => (
                                        <SelectItem key={loc.key} value={loc.key}>{loc.label} ({loc.key})</SelectItem>
                                    ))}
                                    <SelectItem value="custom">Custom (Type manually below)</SelectItem>
                                </SelectContent>
                            </Select>
                            {(!PREDEFINED_LOCATIONS.some(l => l.key === formData.placement_key) || formData.placement_key === 'custom') && (
                                <Input 
                                    className="mt-2" 
                                    placeholder="Enter custom key (e.g. my_custom_spot)"
                                    value={formData.placement_key === 'custom' ? '' : formData.placement_key}
                                    onChange={(e) => setFormData({...formData, placement_key: e.target.value})}
                                    disabled={!!editingAd}
                                />
                            )}
                        </div>

                        <div className="space-y-2">
                            <Label>Ad Type</Label>
                            <div className="flex gap-4">
                                <div className={`border rounded-md p-3 cursor-pointer flex-1 text-center ${formData.type === 'code' ? 'border-primary bg-primary/5' : ''}`} onClick={() => setFormData({...formData, type: 'code'})}>
                                    <Code className="mx-auto mb-1" />
                                    <span className="text-sm font-bold">Script / HTML</span>
                                </div>
                                <div className={`border rounded-md p-3 cursor-pointer flex-1 text-center ${formData.type === 'image' ? 'border-primary bg-primary/5' : ''}`} onClick={() => setFormData({...formData, type: 'image'})}>
                                    <ImageIcon className="mx-auto mb-1" />
                                    <span className="text-sm font-bold">Custom Image</span>
                                </div>
                            </div>
                        </div>

                        {formData.type === 'code' ? (
                            <div className="space-y-2">
                                <Label>Ad Code (HTML / JS)</Label>
                                <Textarea 
                                    placeholder="<script>...</script>" 
                                    rows={5}
                                    value={formData.content || ''}
                                    onChange={(e) => setFormData({...formData, content: e.target.value})}
                                    className="font-mono text-xs"
                                />
                            </div>
                        ) : (
                            <div className="space-y-4">
                                <div className="space-y-2">
                                    <Label>Upload Image</Label>
                                    <Input 
                                        type="file" 
                                        accept="image/*"
                                        onChange={(e) => setFormData({...formData, image_file: e.target.files[0]})}
                                    />
                                    {editingAd && editingAd.type === 'image' && (
                                        <div className="mt-2">
                                            <p className="text-xs text-muted-foreground mb-1">Current Image:</p>
                                            <img src={editingAd.content} alt="Current" className="h-20 object-contain border rounded" />
                                        </div>
                                    )}
                                </div>
                                <div className="space-y-2">
                                    <Label>Target URL (Where clicks go)</Label>
                                    <Input 
                                        placeholder="https://example.com" 
                                        value={formData.target_url}
                                        onChange={(e) => setFormData({...formData, target_url: e.target.value})}
                                    />
                                </div>
                            </div>
                        )}

                        <div className="flex items-center justify-between border p-3 rounded-lg">
                            <div className="space-y-0.5">
                                <Label>Active Status</Label>
                                <p className="text-xs text-muted-foreground">Disable to hide without deleting.</p>
                            </div>
                            <Switch 
                                checked={formData.is_active} 
                                onCheckedChange={(checked) => setFormData({...formData, is_active: checked})}
                            />
                        </div>

                        <DialogFooter>
                            <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>Cancel</Button>
                            <Button type="submit" disabled={isSaving}>
                                {isSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                                Save Placement
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>
        </AdminLayout>
    );
}