import { getSmsLogs } from "@/lib/sms/actions"
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/components/ui/table"
import { Badge } from "@/components/ui/badge"
import { format } from "date-fns"
import { tr } from "date-fns/locale"

export default async function SmsLogsPage() {
    const { data: logs, error } = await getSmsLogs(100)

    if (error) {
        return <div className="p-8">Hata: {error}</div>
    }

    return (
        <div className="flex-1 space-y-4 p-4 pt-6 md:p-8">
            <h2 className="text-2xl md:text-3xl font-bold tracking-tight">SMS Geçmişi</h2>
            <p className="text-muted-foreground">Son gönderilen mesajların durumu.</p>

            <div className="rounded-md border overflow-x-auto">
                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead className="w-[180px]">Tarih</TableHead>
                            <TableHead>Numara</TableHead>
                            <TableHead>Mesaj</TableHead>
                            <TableHead>Durum</TableHead>
                            <TableHead className="text-right">Kod</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {logs?.length === 0 && (
                            <TableRow>
                                <TableCell colSpan={5} className="h-24 text-center">
                                    Kayıt bulunamadı.
                                </TableCell>
                            </TableRow>
                        )}
                        {logs?.map((log) => (
                            <TableRow key={log.id}>
                                <TableCell className="font-medium">
                                    {log.created_at ? format(new Date(log.created_at), "dd MMM yyyy HH:mm", { locale: tr }) : "-"}
                                </TableCell>
                                <TableCell>{log.phone}</TableCell>
                                <TableCell className="max-w-[300px] truncate" title={log.message}>{log.message}</TableCell>
                                <TableCell>
                                    <Badge variant={log.status === 'success' ? 'default' : 'destructive'}>
                                        {log.status === 'success' ? 'Başarılı' : 'Hatalı'}
                                    </Badge>
                                </TableCell>
                                <TableCell className="text-right font-mono text-xs">{log.response_code}</TableCell>
                            </TableRow>
                        ))}
                    </TableBody>
                </Table>
            </div>
        </div>
    )
}
