'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { ArrowLeft, Trash2, Bell, User, Pencil } from 'lucide-react';
import { toast } from 'sonner';

import { notificationsApi } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';

export function NotificationDetailClient() {
  const params = useParams();
  const router = useRouter();
  const queryClient = useQueryClient();
  const notificationId = Number(params.id);

  const { data: notification, isLoading, error } = useQuery({
    queryKey: ['notification', notificationId],
    queryFn: () => notificationsApi.get(notificationId),
    enabled: !!notificationId,
  });

  const deleteMutation = useMutation({
    mutationFn: () => notificationsApi.delete(notificationId),
    onSuccess: () => {
      toast.success('Notification deleted successfully');
      queryClient.invalidateQueries({ queryKey: ['notifications'] });
      router.push('/notifications');
    },
    onError: () => {
      toast.error('Failed to delete notification');
    },
  });

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-muted-foreground">Loading...</div>
      </div>
    );
  }

  if (error || !notification) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-red-500">Failed to load notification</div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="icon" asChild>
            <Link href="/notifications">
              <ArrowLeft className="h-4 w-4" />
            </Link>
          </Button>
          <div>
            <div className="flex items-center gap-2">
              <Bell className="h-5 w-5 text-muted-foreground" />
              <h1 className="text-2xl font-bold">{notification.title}</h1>
            </div>
            <p className="text-muted-foreground">{notification.notification_type}</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" asChild>
            <Link href={`/notifications/${notificationId}/edit`}>
              <Pencil className="mr-2 h-4 w-4" />
              Edit
            </Link>
          </Button>
          <Button
            variant="destructive"
            onClick={() => {
              if (confirm('Are you sure you want to delete this notification?')) {
                deleteMutation.mutate();
              }
            }}
            disabled={deleteMutation.isPending}
          >
            <Trash2 className="mr-2 h-4 w-4" />
            Delete
          </Button>
        </div>
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        {/* Notification Content */}
        <Card>
          <CardHeader>
            <CardTitle>Content</CardTitle>
            <CardDescription>Notification message details</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <div className="text-sm font-medium text-muted-foreground">Title</div>
              <div className="font-medium">{notification.title}</div>
            </div>
            <div>
              <div className="text-sm font-medium text-muted-foreground">Body</div>
              <div className="whitespace-pre-wrap">{notification.body}</div>
            </div>
            {notification.data && notification.data !== '{}' && (
              <div>
                <div className="text-sm font-medium text-muted-foreground">Data</div>
                <pre className="text-sm bg-muted p-2 rounded overflow-x-auto">
                  {JSON.stringify(JSON.parse(notification.data), null, 2)}
                </pre>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Status & User Info */}
        <Card>
          <CardHeader>
            <CardTitle>Details</CardTitle>
            <CardDescription>Status and recipient information</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center gap-2">
              <User className="h-4 w-4 text-muted-foreground" />
              <div>
                <div className="font-medium">{notification.username}</div>
                <div className="text-sm text-muted-foreground">{notification.user_email}</div>
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <div className="text-sm font-medium text-muted-foreground">Type</div>
                <Badge variant="outline">{notification.notification_type}</Badge>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Status</div>
                <div className="flex gap-2">
                  <Badge variant={notification.sent ? 'default' : 'secondary'}>
                    {notification.sent ? 'Sent' : 'Pending'}
                  </Badge>
                  <Badge variant={notification.read ? 'default' : 'outline'}>
                    {notification.read ? 'Read' : 'Unread'}
                  </Badge>
                </div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Created</div>
                <div>{new Date(notification.created_at).toLocaleString()}</div>
              </div>
              {notification.sent_at && (
                <div>
                  <div className="text-sm font-medium text-muted-foreground">Sent At</div>
                  <div>{new Date(notification.sent_at).toLocaleString()}</div>
                </div>
              )}
              {notification.read_at && (
                <div>
                  <div className="text-sm font-medium text-muted-foreground">Read At</div>
                  <div>{new Date(notification.read_at).toLocaleString()}</div>
                </div>
              )}
              {notification.task_id && (
                <div>
                  <div className="text-sm font-medium text-muted-foreground">Related Task</div>
                  <Link href={`/tasks/${notification.task_id}`} className="text-blue-600 hover:underline">
                    Task #{notification.task_id}
                  </Link>
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
