'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { ColumnDef } from '@tanstack/react-table';
import Link from 'next/link';
import { MoreHorizontal, Trash2, Clock } from 'lucide-react';

import { notificationPrefsApi, type NotificationPreference } from '@/lib/api';

// Helper function to format UTC hour for display
function formatHour(hour: number | null): string {
  if (hour === null) return '-';
  const h = hour % 12 || 12;
  const ampm = hour < 12 ? 'AM' : 'PM';
  return `${h}:00 ${ampm}`;
}
import { DataTable } from '@/components/data-table';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { toast } from 'sonner';

export default function NotificationPrefsPage() {
  const [deleteId, setDeleteId] = useState<number | null>(null);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [search, setSearch] = useState('');
  const queryClient = useQueryClient();

  const { data, isLoading } = useQuery({
    queryKey: ['notification-prefs', page, pageSize, search],
    queryFn: () => notificationPrefsApi.list({
      page,
      per_page: pageSize,
      search: search || undefined,
      sort_by: 'user_id',
      sort_dir: 'asc',
    }),
  });

  const deleteMutation = useMutation({
    mutationFn: notificationPrefsApi.delete,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['notification-prefs'] });
      toast.success('Notification preference deleted');
      setDeleteId(null);
    },
    onError: () => {
      toast.error('Failed to delete notification preference');
    },
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: number; data: Parameters<typeof notificationPrefsApi.update>[1] }) =>
      notificationPrefsApi.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['notification-prefs'] });
      toast.success('Preference updated');
    },
    onError: () => {
      toast.error('Failed to update preference');
    },
  });

  const handleToggle = (id: number, field: string, currentValue: boolean) => {
    updateMutation.mutate({
      id,
      data: { [field]: !currentValue },
    });
  };

  const columns: ColumnDef<NotificationPreference>[] = [
    {
      accessorKey: 'id',
      header: 'ID',
      cell: ({ row }) => (
        <span className="font-mono text-sm text-muted-foreground">
          {row.original.id}
        </span>
      ),
    },
    {
      accessorKey: 'username',
      header: 'User',
      cell: ({ row }) => (
        <Link
          href={`/users/${row.original.user_id}`}
          className="font-medium text-blue-600 hover:underline"
        >
          {row.original.username}
        </Link>
      ),
    },
    {
      accessorKey: 'email',
      header: 'Email',
    },
    {
      accessorKey: 'task_due_soon',
      header: 'Due Soon',
      cell: ({ row }) => (
        <Switch
          checked={row.original.task_due_soon}
          onCheckedChange={() => handleToggle(row.original.id, 'task_due_soon', row.original.task_due_soon)}
        />
      ),
    },
    {
      accessorKey: 'task_overdue',
      header: 'Overdue',
      cell: ({ row }) => (
        <Switch
          checked={row.original.task_overdue}
          onCheckedChange={() => handleToggle(row.original.id, 'task_overdue', row.original.task_overdue)}
        />
      ),
    },
    {
      accessorKey: 'task_completed',
      header: 'Completed',
      cell: ({ row }) => (
        <Switch
          checked={row.original.task_completed}
          onCheckedChange={() => handleToggle(row.original.id, 'task_completed', row.original.task_completed)}
        />
      ),
    },
    {
      accessorKey: 'task_assigned',
      header: 'Assigned',
      cell: ({ row }) => (
        <Switch
          checked={row.original.task_assigned}
          onCheckedChange={() => handleToggle(row.original.id, 'task_assigned', row.original.task_assigned)}
        />
      ),
    },
    {
      accessorKey: 'residence_shared',
      header: 'Shared',
      cell: ({ row }) => (
        <Switch
          checked={row.original.residence_shared}
          onCheckedChange={() => handleToggle(row.original.id, 'residence_shared', row.original.residence_shared)}
        />
      ),
    },
    {
      accessorKey: 'warranty_expiring',
      header: 'Warranty',
      cell: ({ row }) => (
        <Switch
          checked={row.original.warranty_expiring}
          onCheckedChange={() => handleToggle(row.original.id, 'warranty_expiring', row.original.warranty_expiring)}
        />
      ),
    },
    {
      accessorKey: 'daily_digest',
      header: 'Daily Digest',
      cell: ({ row }) => (
        <Switch
          checked={row.original.daily_digest}
          onCheckedChange={() => handleToggle(row.original.id, 'daily_digest', row.original.daily_digest)}
        />
      ),
    },
    {
      accessorKey: 'email_task_completed',
      header: 'Email: Completed',
      cell: ({ row }) => (
        <Switch
          checked={row.original.email_task_completed}
          onCheckedChange={() => handleToggle(row.original.id, 'email_task_completed', row.original.email_task_completed)}
        />
      ),
    },
    {
      accessorKey: 'timezone',
      header: 'Timezone',
      cell: ({ row }) => (
        <span className="text-sm">
          {row.original.timezone || <span className="text-muted-foreground">-</span>}
        </span>
      ),
    },
    {
      id: 'notification_times',
      header: () => (
        <div className="flex items-center gap-1">
          <Clock className="h-4 w-4" />
          <span>Custom Times (UTC)</span>
        </div>
      ),
      cell: ({ row }) => {
        const { task_due_soon_hour, task_overdue_hour, warranty_expiring_hour, daily_digest_hour } = row.original;
        const hasCustomTimes = task_due_soon_hour !== null || task_overdue_hour !== null || warranty_expiring_hour !== null || daily_digest_hour !== null;

        if (!hasCustomTimes) {
          return <span className="text-muted-foreground text-sm">Default</span>;
        }

        return (
          <div className="text-sm space-y-0.5">
            {task_due_soon_hour !== null && (
              <div className="text-xs">
                <span className="text-muted-foreground">Due Soon:</span> {formatHour(task_due_soon_hour)}
              </div>
            )}
            {task_overdue_hour !== null && (
              <div className="text-xs">
                <span className="text-muted-foreground">Overdue:</span> {formatHour(task_overdue_hour)}
              </div>
            )}
            {warranty_expiring_hour !== null && (
              <div className="text-xs">
                <span className="text-muted-foreground">Warranty:</span> {formatHour(warranty_expiring_hour)}
              </div>
            )}
            {daily_digest_hour !== null && (
              <div className="text-xs">
                <span className="text-muted-foreground">Daily Digest:</span> {formatHour(daily_digest_hour)}
              </div>
            )}
          </div>
        );
      },
    },
    {
      accessorKey: 'created_at',
      header: 'Created',
      cell: ({ row }) => new Date(row.original.created_at).toLocaleDateString(),
    },
    {
      id: 'actions',
      cell: ({ row }) => {
        const pref = row.original;
        return (
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="ghost" className="h-8 w-8 p-0">
                <span className="sr-only">Open menu</span>
                <MoreHorizontal className="h-4 w-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuLabel>Actions</DropdownMenuLabel>
              <DropdownMenuSeparator />
              <DropdownMenuItem asChild>
                <Link href={`/users/${pref.user_id}`}>View User</Link>
              </DropdownMenuItem>
              <DropdownMenuItem
                className="text-destructive"
                onClick={() => setDeleteId(pref.id)}
              >
                <Trash2 className="mr-2 h-4 w-4" />
                Delete
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        );
      },
    },
  ];

  return (
    <div className="p-6">
      <div className="flex justify-between items-center mb-6">
        <div>
          <h1 className="text-2xl font-bold">Notification Preferences</h1>
          <p className="text-muted-foreground">
            Manage user notification preferences for push notifications and emails
          </p>
        </div>
      </div>

      <DataTable
        columns={columns}
        data={data?.data || []}
        totalCount={data?.total || 0}
        page={page}
        pageSize={pageSize}
        onPageChange={setPage}
        onPageSizeChange={setPageSize}
        searchValue={search}
        onSearchChange={setSearch}
        isLoading={isLoading}
        searchPlaceholder="Search by username or email..."
      />

      <AlertDialog open={deleteId !== null} onOpenChange={() => setDeleteId(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Notification Preference?</AlertDialogTitle>
            <AlertDialogDescription>
              This will remove the notification preference for this user. They will need to set up
              their preferences again.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              onClick={() => deleteId && deleteMutation.mutate(deleteId)}
            >
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
