'use client';

import { useState } from 'react';
import { toast } from 'sonner';
import { approveKomentar, unapproveKomentar, deleteKomentar } from '@/lib/admin-actions';
import { Button } from '@/components/ui/button';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { CheckCircle2, XCircle, Trash2, MessageSquare, Eye } from 'lucide-react';
import { format } from 'date-fns';
import { id } from 'date-fns/locale';
import { Badge } from '@/components/ui/badge';

export default function KomentarTable({ initialData }: { initialData: any[] }) {
    const [data, setData] = useState(initialData);
    const [previewItem, setPreviewItem] = useState<any>(null);
    const [loadingId, setLoadingId] = useState<string | null>(null);

    const handleApprove = async (item: any) => {
        setLoadingId(item.id);
        try {
            if (item.isApproved) {
                const res = await unapproveKomentar(item.id);
                if (res.success) {
                    toast.success(res.message);
                    setData((prev) => prev.map((d) => (d.id === item.id ? { ...d, isApproved: false } : d)));
                } else {
                    toast.error(res.message);
                }
            } else {
                const res = await approveKomentar(item.id);
                if (res.success) {
                    toast.success(res.message);
                    setData((prev) => prev.map((d) => (d.id === item.id ? { ...d, isApproved: true } : d)));
                } else {
                    toast.error(res.message);
                }
            }
        } finally {
            setLoadingId(null);
        }
    };

    const handleDelete = async (itemId: string) => {
        if (!confirm('Yakin ingin menghapus komentar ini secara permanen?')) return;
        setLoadingId(itemId);
        try {
            const res = await deleteKomentar(itemId);
            if (res.success) {
                toast.success(res.message);
                setData((prev) => prev.filter((d) => d.id !== itemId));
            } else {
                toast.error(res.message);
            }
        } finally {
            setLoadingId(null);
        }
    };

    const approved = data.filter((d) => d.isApproved).length;
    const pending = data.filter((d) => !d.isApproved).length;

    return (
        <div className="space-y-4">
            {/* Header */}
            <div className="flex justify-between items-center">
                <div className="flex items-center gap-3">
                    <MessageSquare className="h-6 w-6 text-primary" />
                    <h2 className="text-xl font-bold">Moderasi Komentar Beranda</h2>
                </div>
                <div className="flex items-center gap-3">
                    <span className="flex items-center gap-1.5 text-sm text-muted-foreground">
                        <span className="h-2 w-2 rounded-full bg-green-500 inline-block" />
                        {approved} disetujui
                    </span>
                    <span className="flex items-center gap-1.5 text-sm text-muted-foreground">
                        <span className="h-2 w-2 rounded-full bg-yellow-500 inline-block" />
                        {pending} menunggu
                    </span>
                </div>
            </div>

            <div className="rounded-md border bg-card">
                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead>Nama</TableHead>
                            <TableHead>Isi Komentar</TableHead>
                            <TableHead>Status</TableHead>
                            <TableHead>Waktu</TableHead>
                            <TableHead className="text-right">Aksi</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {data.length === 0 ? (
                            <TableRow>
                                <TableCell colSpan={5} className="text-center py-10 text-muted-foreground">
                                    Belum ada komentar masuk.
                                </TableCell>
                            </TableRow>
                        ) : (
                            data.map((item) => (
                                <TableRow key={item.id} className={!item.isApproved ? 'bg-yellow-500/5' : ''}>
                                    <TableCell className="font-medium whitespace-nowrap">{item.nama}</TableCell>
                                    <TableCell className="max-w-[320px]">
                                        <p className="text-sm text-muted-foreground line-clamp-2">{item.isi}</p>
                                    </TableCell>
                                    <TableCell>
                                        {item.isApproved ? (
                                            <Badge variant="outline" className="border-green-500/50 text-green-400 bg-green-500/10 gap-1">
                                                <CheckCircle2 className="h-3 w-3" />
                                                Disetujui
                                            </Badge>
                                        ) : (
                                            <Badge variant="outline" className="border-yellow-500/50 text-yellow-400 bg-yellow-500/10 gap-1">
                                                <XCircle className="h-3 w-3" />
                                                Menunggu
                                            </Badge>
                                        )}
                                    </TableCell>
                                    <TableCell className="text-sm text-muted-foreground whitespace-nowrap">
                                        {format(new Date(item.createdAt), 'dd MMM yyyy, HH:mm', { locale: id })}
                                    </TableCell>
                                    <TableCell className="text-right">
                                        <div className="flex items-center justify-end gap-1.5">
                                            {/* Preview full text */}
                                            <Button
                                                variant="outline"
                                                size="icon"
                                                title="Lihat isi lengkap"
                                                onClick={() => setPreviewItem(item)}
                                            >
                                                <Eye className="h-4 w-4 text-muted-foreground" />
                                            </Button>

                                            {/* Approve / Unapprove toggle */}
                                            <Button
                                                variant="outline"
                                                size="icon"
                                                disabled={loadingId === item.id}
                                                title={item.isApproved ? 'Cabut Persetujuan' : 'Setujui Komentar'}
                                                className={
                                                    item.isApproved
                                                        ? 'text-yellow-500 hover:bg-yellow-500/10 border-yellow-500/30'
                                                        : 'text-green-500 hover:bg-green-500/10 border-green-500/30'
                                                }
                                                onClick={() => handleApprove(item)}
                                            >
                                                {item.isApproved ? (
                                                    <XCircle className="h-4 w-4" />
                                                ) : (
                                                    <CheckCircle2 className="h-4 w-4" />
                                                )}
                                            </Button>

                                            {/* Delete */}
                                            <Button
                                                variant="outline"
                                                size="icon"
                                                disabled={loadingId === item.id}
                                                className="text-destructive hover:bg-destructive/10"
                                                title="Hapus Komentar"
                                                onClick={() => handleDelete(item.id)}
                                            >
                                                <Trash2 className="h-4 w-4" />
                                            </Button>
                                        </div>
                                    </TableCell>
                                </TableRow>
                            ))
                        )}
                    </TableBody>
                </Table>
            </div>

            {/* Full Text Preview Dialog */}
            <Dialog open={!!previewItem} onOpenChange={() => setPreviewItem(null)}>
                <DialogContent className="max-w-md">
                    <DialogHeader>
                        <DialogTitle className="flex items-center gap-2">
                            <MessageSquare className="h-4 w-4" />
                            Komentar dari{' '}
                            <span className="text-primary">{previewItem?.nama}</span>
                        </DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4">
                        <p className="text-sm leading-relaxed whitespace-pre-wrap text-foreground bg-muted/30 rounded-lg p-4 border border-border">
                            {previewItem?.isi}
                        </p>
                        <div className="flex items-center justify-between text-xs text-muted-foreground">
                            <span>
                                {previewItem?.createdAt &&
                                    format(new Date(previewItem.createdAt), 'dd MMMM yyyy, HH:mm', { locale: id })}
                            </span>
                            {previewItem?.isApproved ? (
                                <Badge variant="outline" className="border-green-500/50 text-green-400 text-xs">
                                    ✓ Sudah Disetujui
                                </Badge>
                            ) : (
                                <Badge variant="outline" className="border-yellow-500/50 text-yellow-400 text-xs">
                                    ⏳ Menunggu Moderasi
                                </Badge>
                            )}
                        </div>
                        <div className="flex gap-2">
                            <Button
                                variant="outline"
                                className="flex-1"
                                onClick={() => {
                                    handleApprove(previewItem);
                                    setPreviewItem(null);
                                }}
                            >
                                {previewItem?.isApproved ? 'Cabut Persetujuan' : 'Setujui Komentar'}
                            </Button>
                            <Button
                                variant="outline"
                                className="text-destructive hover:bg-destructive/10"
                                onClick={() => {
                                    handleDelete(previewItem?.id);
                                    setPreviewItem(null);
                                }}
                            >
                                <Trash2 className="h-4 w-4 mr-1" />
                                Hapus
                            </Button>
                        </div>
                    </div>
                </DialogContent>
            </Dialog>
        </div>
    );
}
