'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import Link from 'next/link';
import Image from 'next/image';
import { CheckCircle, Trash2, Search, ChevronLeft, ChevronRight, ExternalLink, Image as ImageIcon } from 'lucide-react';
import { toast } from 'sonner';

import { completionsApi, type TaskCompletion, type CompletionListParams } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';

export default function CompletionsPage() {
  const queryClient = useQueryClient();
  const [params, setParams] = useState<CompletionListParams>({
    page: 1,
    per_page: 20,
  });
  const [search, setSearch] = useState('');
  const [selectedRows, setSelectedRows] = useState<number[]>([]);

  const { data, isLoading, error } = useQuery({
    queryKey: ['completions', params],
    queryFn: () => completionsApi.list(params),
  });

  const deleteMutation = useMutation({
    mutationFn: (id: number) => completionsApi.delete(id),
    onSuccess: () => {
      toast.success('Completion deleted successfully');
      queryClient.invalidateQueries({ queryKey: ['completions'] });
    },
    onError: () => {
      toast.error('Failed to delete completion');
    },
  });

  const bulkDeleteMutation = useMutation({
    mutationFn: (ids: number[]) => completionsApi.bulkDelete(ids),
    onSuccess: () => {
      toast.success('Completions deleted successfully');
      queryClient.invalidateQueries({ queryKey: ['completions'] });
      setSelectedRows([]);
    },
    onError: () => {
      toast.error('Failed to delete completions');
    },
  });

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    setParams({ ...params, search, page: 1 });
  };

  const handleSelectAll = (checked: boolean) => {
    if (checked && data?.data) {
      setSelectedRows(data.data.map((c) => c.id));
    } else {
      setSelectedRows([]);
    }
  };

  const handleSelectRow = (id: number, checked: boolean) => {
    if (checked) {
      setSelectedRows([...selectedRows, id]);
    } else {
      setSelectedRows(selectedRows.filter((rowId) => rowId !== id));
    }
  };

  const totalPages = data ? Math.ceil(data.total / (params.per_page || 20)) : 0;

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

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Task Completions</h1>
          <p className="text-muted-foreground">
            View all completed tasks with photos and notes
          </p>
        </div>
      </div>

      {/* Search and Bulk Actions */}
      <div className="flex items-center justify-between gap-4">
        <form onSubmit={handleSearch} className="flex gap-2 flex-1 max-w-md">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              placeholder="Search by task title, username, or notes..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="pl-9"
            />
          </div>
          <Button type="submit" variant="secondary">
            Search
          </Button>
        </form>

        {selectedRows.length > 0 && (
          <AlertDialog>
            <AlertDialogTrigger asChild>
              <Button variant="destructive">
                <Trash2 className="mr-2 h-4 w-4" />
                Delete Selected ({selectedRows.length})
              </Button>
            </AlertDialogTrigger>
            <AlertDialogContent>
              <AlertDialogHeader>
                <AlertDialogTitle>Delete Selected Completions?</AlertDialogTitle>
                <AlertDialogDescription>
                  This will permanently delete {selectedRows.length} completion record(s). This action cannot be undone.
                </AlertDialogDescription>
              </AlertDialogHeader>
              <AlertDialogFooter>
                <AlertDialogCancel>Cancel</AlertDialogCancel>
                <AlertDialogAction
                  onClick={() => bulkDeleteMutation.mutate(selectedRows)}
                  className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                >
                  Delete
                </AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>
        )}
      </div>

      {/* Table */}
      <div className="rounded-md border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-12">
                <Checkbox
                  checked={
                    data?.data &&
                    data.data.length > 0 &&
                    selectedRows.length === data.data.length
                  }
                  onCheckedChange={handleSelectAll}
                />
              </TableHead>
              <TableHead>ID</TableHead>
              <TableHead>Task</TableHead>
              <TableHead>Residence</TableHead>
              <TableHead>Completed By</TableHead>
              <TableHead>Completed At</TableHead>
              <TableHead>Cost</TableHead>
              <TableHead>Photo</TableHead>
              <TableHead>Created</TableHead>
              <TableHead className="w-24">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {isLoading ? (
              <TableRow>
                <TableCell colSpan={8} className="text-center py-8">
                  Loading...
                </TableCell>
              </TableRow>
            ) : data?.data?.length === 0 ? (
              <TableRow>
                <TableCell colSpan={8} className="text-center py-8">
                  No completions found
                </TableCell>
              </TableRow>
            ) : (
              data?.data?.map((completion) => (
                <TableRow key={completion.id}>
                  <TableCell>
                    <Checkbox
                      checked={selectedRows.includes(completion.id)}
                      onCheckedChange={(checked) =>
                        handleSelectRow(completion.id, checked as boolean)
                      }
                    />
                  </TableCell>
                  <TableCell className="font-mono text-sm text-muted-foreground">{completion.id}</TableCell>
                  <TableCell>
                    <Link
                      href={`/completions/${completion.id}`}
                      className="font-medium text-blue-600 hover:underline"
                    >
                      {completion.task_title}
                    </Link>
                    {completion.notes && (
                      <p className="text-xs text-muted-foreground mt-1 truncate max-w-xs">
                        {completion.notes}
                      </p>
                    )}
                  </TableCell>
                  <TableCell>
                    <Link
                      href={`/residences/${completion.residence_id}`}
                      className="text-blue-600 hover:underline"
                    >
                      {completion.residence_name}
                    </Link>
                  </TableCell>
                  <TableCell>
                    <Link
                      href={`/users/${completion.completed_by_id}`}
                      className="text-blue-600 hover:underline"
                    >
                      {completion.completed_by}
                    </Link>
                  </TableCell>
                  <TableCell>
                    {new Date(completion.completed_at).toLocaleDateString()}
                  </TableCell>
                  <TableCell>
                    {completion.actual_cost ? (
                      <Badge variant="outline">${completion.actual_cost}</Badge>
                    ) : (
                      <span className="text-muted-foreground">-</span>
                    )}
                  </TableCell>
                  <TableCell>
                    {completion.images && completion.images.length > 0 ? (
                      <Dialog>
                        <DialogTrigger asChild>
                          <Button variant="ghost" size="sm">
                            <ImageIcon className="h-4 w-4 mr-1" />
                            {completion.images.length} {completion.images.length === 1 ? 'Photo' : 'Photos'}
                          </Button>
                        </DialogTrigger>
                        <DialogContent className="max-w-2xl">
                          <DialogHeader>
                            <DialogTitle>Completion Photos ({completion.images.length})</DialogTitle>
                          </DialogHeader>
                          <div className="space-y-4 max-h-[60vh] overflow-y-auto">
                            {completion.images.map((image, index) => (
                              <div key={image.id || index} className="space-y-2">
                                <div className="relative aspect-video">
                                  <img
                                    src={image.image_url}
                                    alt={image.caption || `Completion photo ${index + 1}`}
                                    className="object-contain w-full h-full rounded-lg"
                                  />
                                </div>
                                {image.caption && (
                                  <p className="text-sm text-muted-foreground">{image.caption}</p>
                                )}
                                <a
                                  href={image.image_url}
                                  target="_blank"
                                  rel="noopener noreferrer"
                                  className="flex items-center gap-1 text-sm text-blue-600 hover:underline"
                                >
                                  <ExternalLink className="h-3 w-3" />
                                  Open in new tab
                                </a>
                              </div>
                            ))}
                          </div>
                        </DialogContent>
                      </Dialog>
                    ) : (
                      <span className="text-muted-foreground">-</span>
                    )}
                  </TableCell>
                  <TableCell>
                    {new Date(completion.created_at).toLocaleDateString()}
                  </TableCell>
                  <TableCell>
                    <AlertDialog>
                      <AlertDialogTrigger asChild>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="text-red-600 hover:text-red-700 hover:bg-red-50"
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </AlertDialogTrigger>
                      <AlertDialogContent>
                        <AlertDialogHeader>
                          <AlertDialogTitle>Delete Completion?</AlertDialogTitle>
                          <AlertDialogDescription>
                            This will permanently delete this completion record. This action cannot be undone.
                          </AlertDialogDescription>
                        </AlertDialogHeader>
                        <AlertDialogFooter>
                          <AlertDialogCancel>Cancel</AlertDialogCancel>
                          <AlertDialogAction
                            onClick={() => deleteMutation.mutate(completion.id)}
                            className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                          >
                            Delete
                          </AlertDialogAction>
                        </AlertDialogFooter>
                      </AlertDialogContent>
                    </AlertDialog>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* Pagination */}
      {data && totalPages > 1 && (
        <div className="flex items-center justify-between">
          <div className="text-sm text-muted-foreground">
            Showing {((params.page || 1) - 1) * (params.per_page || 20) + 1} to{' '}
            {Math.min(
              (params.page || 1) * (params.per_page || 20),
              data.total
            )}{' '}
            of {data.total} completions
          </div>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              disabled={(params.page || 1) <= 1}
              onClick={() =>
                setParams({ ...params, page: (params.page || 1) - 1 })
              }
            >
              <ChevronLeft className="h-4 w-4" />
              Previous
            </Button>
            <Button
              variant="outline"
              size="sm"
              disabled={(params.page || 1) >= totalPages}
              onClick={() =>
                setParams({ ...params, page: (params.page || 1) + 1 })
              }
            >
              Next
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}
