'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, Plus, Trash2 } from 'lucide-react';

import { tasksApi } from '@/lib/api';
import type { Task } from '@/types/models';
import { DataTable } from '@/components/data-table';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { toast } from 'sonner';

const columns: ColumnDef<Task>[] = [
  {
    accessorKey: 'id',
    header: 'ID',
    cell: ({ row }) => (
      <span className="font-mono text-sm text-muted-foreground">
        {row.original.id}
      </span>
    ),
  },
  {
    accessorKey: 'title',
    header: 'Title',
    cell: ({ row }) => (
      <Link
        href={`/tasks/${row.original.id}`}
        className="font-medium text-blue-600 hover:underline"
      >
        {row.original.title}
      </Link>
    ),
  },
  {
    accessorKey: 'residence_name',
    header: 'Residence',
  },
  {
    accessorKey: 'category_name',
    header: 'Category',
    cell: ({ row }) => row.original.category_name || '-',
  },
  {
    accessorKey: 'priority_name',
    header: 'Priority',
    cell: ({ row }) => row.original.priority_name || '-',
  },
  {
    accessorKey: 'in_progress',
    header: 'In Progress',
    cell: ({ row }) => row.original.in_progress ? '✓' : '—',
  },
  {
    accessorKey: 'due_date',
    header: 'Due Date',
    cell: ({ row }) => row.original.due_date ? new Date(row.original.due_date).toLocaleDateString() : '-',
  },
  {
    accessorKey: 'next_due_date',
    header: 'Next Due',
    cell: ({ row }) => row.original.next_due_date ? new Date(row.original.next_due_date).toLocaleDateString() : '-',
  },
  {
    accessorKey: 'is_cancelled',
    header: 'State',
    cell: ({ row }) => {
      if (row.original.is_cancelled) return <Badge variant="destructive">Cancelled</Badge>;
      if (row.original.is_archived) return <Badge variant="secondary">Archived</Badge>;
      return <Badge variant="default">Active</Badge>;
    },
  },
  {
    accessorKey: 'created_at',
    header: 'Created',
    cell: ({ row }) => new Date(row.original.created_at).toLocaleDateString(),
  },
  {
    id: 'actions',
    cell: ({ row }) => {
      const task = 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>
            <DropdownMenuItem asChild>
              <Link href={`/tasks/${task.id}`}>View details</Link>
            </DropdownMenuItem>
            <DropdownMenuItem asChild>
              <Link href={`/tasks/${task.id}/edit`}>Edit</Link>
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      );
    },
  },
];

export default function TasksPage() {
  const queryClient = useQueryClient();
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [search, setSearch] = useState('');
  const [selectedRows, setSelectedRows] = useState<Task[]>([]);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);

  const { data, isLoading } = useQuery({
    queryKey: ['tasks', { page, per_page: pageSize, search }],
    queryFn: () => tasksApi.list({ page, per_page: pageSize, search: search || undefined }),
  });

  const bulkDeleteMutation = useMutation({
    mutationFn: (ids: number[]) => tasksApi.bulkDelete(ids),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['tasks'] });
      setSelectedRows([]);
      setShowDeleteDialog(false);
      toast.success(`${selectedRows.length} task(s) archived`);
    },
    onError: () => {
      toast.error('Failed to archive tasks');
    },
  });

  const handleBulkDelete = () => {
    const ids = selectedRows.map((t) => t.id);
    bulkDeleteMutation.mutate(ids);
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Tasks</h1>
          <p className="text-muted-foreground">Manage tasks and maintenance items</p>
        </div>
        <div className="flex items-center gap-2">
          {selectedRows.length > 0 && (
            <Button
              variant="destructive"
              size="sm"
              onClick={() => setShowDeleteDialog(true)}
            >
              <Trash2 className="h-4 w-4 mr-2" />
              Archive ({selectedRows.length})
            </Button>
          )}
          <Button asChild>
            <Link href="/tasks/new">
              <Plus className="h-4 w-4 mr-2" />
              New Task
            </Link>
          </Button>
        </div>
      </div>

      <DataTable
        columns={columns}
        data={data?.data ?? []}
        totalCount={data?.total ?? 0}
        page={page}
        pageSize={pageSize}
        onPageChange={setPage}
        onPageSizeChange={(size) => {
          setPageSize(size);
          setPage(1);
        }}
        searchValue={search}
        onSearchChange={(value) => {
          setSearch(value);
          setPage(1);
        }}
        searchPlaceholder="Search tasks..."
        isLoading={isLoading}
        enableRowSelection
        onRowSelectionChange={setSelectedRows}
      />

      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Archive Tasks</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to archive {selectedRows.length} task(s)?
              This will mark them as archived and cancelled.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleBulkDelete}
              className="bg-red-600 hover:bg-red-700"
            >
              {bulkDeleteMutation.isPending ? 'Archiving...' : 'Archive'}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
