import React, { useState } from 'react';
import { Head, router } from '@inertiajs/react';
import AdminLayout from '@/Layouts/AdminLayout';
import { 
    Plus, 
    Search, 
    GripVertical, 
    Edit2, 
    Trash2, 
    Info,
    ShieldAlert
} from 'lucide-react';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogFooter,
} from "@/components/ui/dialog";

export default function ReportReasons({ reasons }) {
    const [searchTerm, setSearchTerm] = useState('');
    const [isDialogOpen, setIsDialogOpen] = useState(false);
    const [editingReason, setEditingReason] = useState(null);
    const [reasonName, setReasonName] = useState('');
    const [reasonStatus, setReasonStatus] = useState('Active');
    const [reasonType, setReasonType] = useState('Both');
    const [error, setError] = useState('');

    const handleOpenAdd = () => {
        setEditingReason(null);
        setReasonName('');
        setReasonStatus('Active');
        setReasonType('Both');
        setError('');
        setIsDialogOpen(true);
    };

    const handleOpenEdit = (reason) => {
        setEditingReason(reason);
        setReasonName(reason.reason);
        setReasonStatus(reason.status);
        setReasonType(reason.type || 'Both');
        setError('');
        setIsDialogOpen(true);
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        if (!reasonName.trim()) {
            setError('Reason description is required.');
            return;
        }

        if (editingReason) {
            router.post(`/admin/master-data/reasons/${editingReason.id}/update`, {
                reason: reasonName.trim(),
                status: reasonStatus,
                type: reasonType
            }, {
                onSuccess: () => {
                    setIsDialogOpen(false);
                },
                onError: (err) => {
                    setError(err.reason || 'Failed to update reason.');
                }
            });
        } else {
            router.post('/master-data/reasons', {
                reason: reasonName.trim(),
                type: reasonType
            }, {
                onSuccess: () => {
                    setIsDialogOpen(false);
                },
                onError: (err) => {
                    setError(err.reason || 'Failed to add reason.');
                }
            });
        }
    };

    const handleDelete = (id) => {
        if (confirm('Are you sure you want to delete this report reason?')) {
            router.delete(`/admin/master-data/reasons/${id}`);
        }
    };

    const filteredReasons = reasons.filter(reason => 
        reason.reason.toLowerCase().includes(searchTerm.toLowerCase()) ||
        reason.type.toLowerCase().includes(searchTerm.toLowerCase())
    );

    const getTypeBadgeClass = (type) => {
        switch (type) {
            case 'Chat':
                return 'bg-blue-50 text-blue-700 border border-blue-200';
            case 'Review':
                return 'bg-purple-50 text-purple-700 border border-purple-200';
            case 'Support':
                return 'bg-amber-50 text-amber-700 border border-amber-200';
            default:
                return 'bg-teal-50 text-teal-700 border border-teal-200';
        }
    };

    return (
        <AdminLayout title="Reason Master">
            <Head title="Master Data - Reason Master" />

            <div className="max-w-4xl mx-auto space-y-6">
                {/* Header Actions */}
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                    <div className="relative flex-1 max-w-sm">
                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                        <input 
                            type="text" 
                            placeholder="Find reason..." 
                            value={searchTerm}
                            onChange={e => setSearchTerm(e.target.value)}
                            className="w-full pl-10 pr-4 py-2.5 bg-white border border-slate-200 rounded-xl text-sm font-medium focus:ring-4 focus:ring-teal-500/10 outline-none transition-all"
                        />
                    </div>
                    <button 
                        onClick={handleOpenAdd}
                        className="bg-[#0F6E56] text-white px-6 py-2.5 rounded-xl text-sm font-bold flex items-center justify-center space-x-2 hover:bg-[#085041] transition-all shadow-lg shadow-teal-500/10 cursor-pointer"
                    >
                        <Plus className="w-4 h-4" />
                        <span>Add Reason</span>
                    </button>
                </div>

                {/* Reasons Card */}
                <div className="bg-white rounded-[24px] border border-slate-200 shadow-sm overflow-hidden">
                    <div className="p-6 border-b border-slate-50 bg-slate-50/30">
                        <div className="flex items-center space-x-3">
                            <div className="p-2 bg-teal-50 rounded-lg">
                                <ShieldAlert className="w-5 h-5 text-[#0F6E56]" />
                            </div>
                            <div>
                                <h2 className="text-sm font-black text-slate-900 uppercase tracking-tight">Reason Master</h2>
                                <p className="text-[10px] text-slate-400 font-bold uppercase tracking-widest mt-0.5">Manage safety & moderation report reasons</p>
                            </div>
                        </div>
                    </div>

                    <Table>
                        <TableHeader>
                            <TableRow className="bg-white hover:bg-white">
                                <TableHead className="w-12"></TableHead>
                                <TableHead className="font-bold text-slate-400 text-[10px] uppercase tracking-widest h-12">Report Reason</TableHead>
                                <TableHead className="font-bold text-slate-400 text-[10px] uppercase tracking-widest h-12">Applicable Type</TableHead>
                                <TableHead className="font-bold text-slate-400 text-[10px] uppercase tracking-widest h-12">Status</TableHead>
                                <TableHead className="font-bold text-slate-400 text-[10px] uppercase tracking-widest h-12 text-right pr-6">Action</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {filteredReasons.length > 0 ? (
                                filteredReasons.map((reason) => (
                                    <TableRow key={reason.id} className="hover:bg-slate-50/50 transition-colors group">
                                        <TableCell className="pl-4">
                                            <GripVertical className="w-4 h-4 text-slate-300" />
                                        </TableCell>
                                        <TableCell className="py-4 font-bold text-slate-900 text-sm">
                                            {reason.reason}
                                        </TableCell>
                                        <TableCell>
                                            <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-[10px] font-black uppercase tracking-tight ${getTypeBadgeClass(reason.type)}`}>
                                                {reason.type}
                                            </span>
                                        </TableCell>
                                        <TableCell>
                                            <span className={`inline-flex items-center px-2 py-0.5 rounded text-[10px] font-black uppercase tracking-tight ${
                                                reason.status === 'Active' 
                                                    ? 'bg-emerald-50 text-emerald-600' 
                                                    : 'bg-slate-100 text-slate-500'
                                            }`}>
                                                {reason.status}
                                            </span>
                                        </TableCell>
                                        <TableCell className="text-right pr-6">
                                            <div className="flex items-center justify-end space-x-1 opacity-0 group-hover:opacity-100 transition-opacity">
                                                <button 
                                                    onClick={() => handleOpenEdit(reason)}
                                                    className="p-2 text-slate-400 hover:text-[#0F6E56] hover:bg-teal-50 rounded-lg transition-all cursor-pointer"
                                                >
                                                    <Edit2 className="w-4 h-4" />
                                                </button>
                                                <button 
                                                    onClick={() => handleDelete(reason.id)}
                                                    className="p-2 text-slate-400 hover:text-rose-500 hover:bg-rose-50 rounded-lg transition-all cursor-pointer"
                                                >
                                                    <Trash2 className="w-4 h-4" />
                                                </button>
                                            </div>
                                        </TableCell>
                                    </TableRow>
                                ))
                            ) : (
                                <TableRow>
                                    <TableCell colSpan={5} className="py-8 text-center text-slate-400 font-bold text-xs">
                                        No reasons match your search.
                                    </TableCell>
                                </TableRow>
                            )}
                        </TableBody>
                    </Table>

                    <div className="p-6 bg-slate-50/50 border-t border-slate-100">
                        <div className="flex items-start space-x-3 text-slate-400">
                            <Info className="w-4 h-4 shrink-0 mt-0.5" />
                            <p className="text-[10px] font-bold uppercase tracking-wide leading-relaxed">
                                Tip: Scoping reasons to "Chat" or "Review" helps filter options on the mobile UI. A reason marked "Both" is displayed for all safety reports.
                            </p>
                        </div>
                    </div>
                </div>
            </div>

            {/* Reason Modal */}
            <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                <DialogContent className="sm:max-w-[400px] rounded-[24px] bg-white">
                    <DialogHeader>
                        <DialogTitle className="text-xl font-black text-slate-900 tracking-tight">
                            {editingReason ? 'Edit Reason' : 'New Reason'}
                        </DialogTitle>
                    </DialogHeader>
                    
                    <form onSubmit={handleSubmit} className="space-y-4">
                        <div className="py-4 space-y-4">
                            <div className="space-y-2">
                                <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-1">Reason Description</label>
                                <input 
                                    className="w-full px-4 py-3 bg-slate-50 border border-slate-100 rounded-xl text-sm font-bold focus:ring-4 focus:ring-teal-500/10 outline-none" 
                                    placeholder="e.g. Abusive behavior" 
                                    value={reasonName}
                                    onChange={e => setReasonName(e.target.value)}
                                />
                                {error && (
                                    <p className="text-xs text-rose-600 font-bold ml-1">{error}</p>
                                )}
                            </div>

                            <div className="space-y-2">
                                <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-1">Applicable Type</label>
                                <select 
                                    className="w-full px-4 py-3 bg-slate-50 border border-slate-100 rounded-xl text-sm font-bold focus:ring-4 focus:ring-teal-500/10 outline-none cursor-pointer animate-none"
                                    value={reasonType}
                                    onChange={e => setReasonType(e.target.value)}
                                >
                                    <option value="Both">Both (Chat & Review)</option>
                                    <option value="Chat">Chat Only</option>
                                    <option value="Review">Review Only</option>
                                    <option value="Support">Support Ticket Only</option>
                                </select>
                            </div>

                            {editingReason && (
                                <div className="space-y-2">
                                    <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-1">Status</label>
                                    <select 
                                        className="w-full px-4 py-3 bg-slate-50 border border-slate-100 rounded-xl text-sm font-bold focus:ring-4 focus:ring-teal-500/10 outline-none cursor-pointer"
                                        value={reasonStatus}
                                        onChange={e => setReasonStatus(e.target.value)}
                                    >
                                        <option value="Active">Active</option>
                                        <option value="Inactive">Inactive</option>
                                    </select>
                                </div>
                            )}
                        </div>

                        <DialogFooter className="sm:justify-end gap-3 pt-4 border-t border-slate-100">
                            <button 
                                type="button"
                                onClick={() => setIsDialogOpen(false)}
                                className="px-6 py-2.5 rounded-xl text-sm font-bold text-slate-400 uppercase tracking-widest hover:bg-slate-50 transition-colors"
                            >
                                Cancel
                            </button>
                            <button 
                                type="submit"
                                className="bg-[#0F6E56] text-white px-8 py-2.5 rounded-xl text-sm font-bold uppercase tracking-widest shadow-lg shadow-teal-500/20 active:scale-95 transition-all cursor-pointer"
                            >
                                {editingReason ? 'Update' : 'Add Reason'}
                            </button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>
        </AdminLayout>
    );
}
