import { useEffect, useMemo, useState } from 'react';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import { useShortcut } from '../hooks/useShortcuts';
import { ChevronLeft, ChevronRight, Trash2, Save } from 'lucide-react';
import { SEVERITY_BG } from '../lib/severityColors';
import { formatDistanceToNow } from 'date-fns';
import { toast } from 'sonner';
import Layout from '../components/Layout';
import SeverityBadge from '../components/SeverityBadge';
import StatusBadge from '../components/StatusBadge';
import Avatar from '../components/Avatar';
import CTISelect from '../components/CTISelect';
import { TicketStatus } from '../types';
import { useAuth } from '../contexts/AuthContext';
import {
  useTicketsPaged,
  useBulkTickets,
  useSavedViews,
  useCreateSavedView,
  useDeleteSavedView,
  useUsers,
} from '../api/queries';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';

const STATUS_TABS: { value: TicketStatus | ''; label: string }[] = [
  { value: '', label: 'All' },
  { value: 'OPEN', label: 'Open' },
  { value: 'IN_PROGRESS', label: 'In progress' },
  { value: 'RESOLVED', label: 'Resolved' },
  { value: 'CLOSED', label: 'Closed' },
];

const PAGE_SIZE = 25;
const BULK_LIMIT = 500;

export default function Tickets() {
  const [params, setParams] = useSearchParams();
  const navigate = useNavigate();
  const { user: authUser } = useAuth();
  const { data: users = [] } = useUsers();

  const status = (params.get('status') ?? '') as TicketStatus | '';
  const severity = params.get('severity') ?? '';
  const assigneeId = params.get('assigneeId') ?? '';
  const categoryId = params.get('categoryId') ?? '';
  const typeId = params.get('typeId') ?? '';
  const itemId = params.get('itemId') ?? '';
  const search = params.get('search') ?? '';
  const page = Math.max(1, Number(params.get('page') ?? '1'));

  const [searchInput, setSearchInput] = useState(search);
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [cursor, setCursor] = useState<number>(-1);
  const [saveOpen, setSaveOpen] = useState(false);
  const [newViewName, setNewViewName] = useState('');
  const [confirmBulk, setConfirmBulk] = useState<
    | { kind: 'close' | 'setSeverity' | 'reassign'; value?: unknown; label: string }
    | null
  >(null);

  useEffect(() => {
    const t = setTimeout(() => {
      if (search !== searchInput) {
        updateParam('search', searchInput);
        updateParam('page', '1');
      }
    }, 250);
    return () => clearTimeout(t);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchInput]);

  const updateParam = (key: string, value: string | null) => {
    setParams(
      (prev) => {
        const next = new URLSearchParams(prev);
        if (value === null || value === '') next.delete(key);
        else next.set(key, value);
        if (key !== 'page') next.delete('page'); // reset page on filter change
        return next;
      },
      { replace: true },
    );
  };

  const queryParams = {
    status: status || undefined,
    severity: severity ? Number(severity) : undefined,
    assigneeId: assigneeId || undefined,
    categoryId: categoryId || undefined,
    typeId: typeId || undefined,
    itemId: itemId || undefined,
    search: search || undefined,
    page,
    pageSize: PAGE_SIZE,
  };

  const { data, isLoading, isFetching } = useTicketsPaged(queryParams);
  const tickets = data?.data ?? [];
  const total = data?.total ?? 0;
  const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));

  const savedViewsQ = useSavedViews();
  const createView = useCreateSavedView();
  const deleteView = useDeleteSavedView();
  const bulk = useBulkTickets();

  const allVisible = tickets.length > 0 && tickets.every((t) => selected.has(t.id));
  const someVisible = tickets.some((t) => selected.has(t.id));

  const toggleAll = () => {
    setSelected((prev) => {
      const next = new Set(prev);
      if (allVisible) tickets.forEach((t) => next.delete(t.id));
      else tickets.forEach((t) => next.add(t.id));
      return next;
    });
  };

  const toggleOne = (id: string) => {
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const clearSelected = () => setSelected(new Set());

  const currentFilters = useMemo(
    () => ({
      status: status || undefined,
      severity: severity ? Number(severity) : undefined,
      assigneeId: assigneeId || undefined,
      categoryId: categoryId || undefined,
      typeId: typeId || undefined,
      itemId: itemId || undefined,
      search: search || undefined,
    }),
    [status, severity, assigneeId, categoryId, typeId, itemId, search],
  );

  const runBulk = async (payload: { action: string; value?: unknown }) => {
    const ids = Array.from(selected).slice(0, BULK_LIMIT);
    try {
      const res = (await bulk.mutateAsync({ ids, ...payload })) as { updated?: number };
      toast.success(`Updated ${res.updated ?? ids.length} ticket${ids.length === 1 ? '' : 's'}`);
      clearSelected();
    } catch (e) {
      toast.error((e as Error).message || 'Bulk action failed');
    } finally {
      setConfirmBulk(null);
    }
  };

  const activeCount = Object.values(currentFilters).filter(Boolean).length;

  const handleSaveView = async () => {
    if (!newViewName.trim()) return;
    try {
      await createView.mutateAsync({
        name: newViewName.trim(),
        filters: currentFilters,
      });
      toast.success('Saved view');
      setNewViewName('');
      setSaveOpen(false);
    } catch (e) {
      toast.error((e as Error).message || 'Failed to save view');
    }
  };

  const applyView = (filters: Record<string, unknown>) => {
    const next = new URLSearchParams();
    Object.entries(filters).forEach(([k, v]) => {
      if (v !== undefined && v !== null && v !== '') next.set(k, String(v));
    });
    setParams(next, { replace: true });
    setSearchInput(String(filters.search ?? ''));
  };

  const agentUsers = users;

  // Keyboard navigation
  useEffect(() => {
    setCursor((c) => (c >= tickets.length ? tickets.length - 1 : c));
  }, [tickets.length]);

  useShortcut('j', (e) => {
    if (tickets.length === 0) return;
    e.preventDefault();
    setCursor((c) => Math.min(tickets.length - 1, c < 0 ? 0 : c + 1));
  }, [tickets.length]);

  useShortcut('k', (e) => {
    if (tickets.length === 0) return;
    e.preventDefault();
    setCursor((c) => Math.max(0, c < 0 ? 0 : c - 1));
  }, [tickets.length]);

  useShortcut('enter', (e) => {
    if (cursor < 0 || cursor >= tickets.length) return;
    e.preventDefault();
    navigate(`/${tickets[cursor].displayId}`);
  }, [cursor, tickets]);

  useShortcut('x', (e) => {
    if (cursor < 0 || cursor >= tickets.length) return;
    e.preventDefault();
    toggleOne(tickets[cursor].id);
  }, [cursor, tickets]);

  return (
    <Layout wide>
      {/* Status tabs */}
      <div className="flex items-center border-b border-border mb-4 -mx-4 px-4 overflow-x-auto">
        {STATUS_TABS.map((tab) => (
          <button
            key={tab.value}
            onClick={() => updateParam('status', tab.value || null)}
            className={`px-3 py-2 text-sm whitespace-nowrap border-b-2 -mb-px transition-colors ${
              status === tab.value
                ? 'border-primary text-foreground font-medium'
                : 'border-transparent text-muted-foreground hover:text-foreground'
            }`}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {/* Filter bar */}
      <div className="flex gap-2 mb-4 flex-wrap items-center">
        <input
          type="search"
          value={searchInput}
          onChange={(e) => setSearchInput(e.target.value)}
          placeholder="Search title, overview, ID…"
          className="flex-1 min-w-48 max-w-xs px-3 py-1.5 rounded-md border border-input bg-background text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-ring"
        />

        <select
          value={severity}
          onChange={(e) => updateParam('severity', e.target.value || null)}
          className="px-3 py-1.5 rounded-md border border-input bg-background text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-ring"
        >
          <option value="">All severities</option>
          {[1, 2, 3, 4, 5].map((s) => (
            <option key={s} value={s}>
              SEV {s}
            </option>
          ))}
        </select>

        <select
          value={assigneeId}
          onChange={(e) => updateParam('assigneeId', e.target.value || null)}
          className="px-3 py-1.5 rounded-md border border-input bg-background text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-ring"
        >
          <option value="">All assignees</option>
          {authUser && (
            <option value={authUser.id}>Me ({authUser.displayName})</option>
          )}
          {agentUsers
            .filter((u) => u.id !== authUser?.id)
            .map((u) => (
              <option key={u.id} value={u.id}>
                {u.displayName}
              </option>
            ))}
        </select>

        <div className="min-w-56">
          <CTISelect
            value={{ categoryId, typeId, itemId }}
            onChange={(cti) => {
              setParams(
                (prev) => {
                  const next = new URLSearchParams(prev);
                  next.delete('page');
                  if (cti.categoryId) next.set('categoryId', cti.categoryId);
                  else next.delete('categoryId');
                  if (cti.typeId) next.set('typeId', cti.typeId);
                  else next.delete('typeId');
                  if (cti.itemId) next.set('itemId', cti.itemId);
                  else next.delete('itemId');
                  return next;
                },
                { replace: true },
              );
            }}
          />
        </div>

        {/* Saved views */}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <button className="px-3 py-1.5 rounded-md border border-input bg-background text-sm hover:bg-accent">
              Saved views
            </button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="w-64">
            <DropdownMenuLabel>Saved views</DropdownMenuLabel>
            <DropdownMenuSeparator />
            {savedViewsQ.data && savedViewsQ.data.length > 0 ? (
              savedViewsQ.data.map((v) => (
                <div
                  key={v.id}
                  className="flex items-center gap-1 px-2 py-1 hover:bg-accent rounded-sm"
                >
                  <button
                    onClick={() => applyView(v.filters)}
                    className="flex-1 text-left text-sm truncate"
                  >
                    {v.name}
                  </button>
                  <button
                    onClick={() => deleteView.mutate(v.id)}
                    aria-label="Delete view"
                    className="text-muted-foreground hover:text-destructive"
                  >
                    <Trash2 size={13} />
                  </button>
                </div>
              ))
            ) : (
              <p className="px-2 py-1 text-xs text-muted-foreground">No saved views yet</p>
            )}
            <DropdownMenuSeparator />
            <DropdownMenuItem
              disabled={activeCount === 0}
              onSelect={() => setSaveOpen(true)}
              className="gap-2"
            >
              <Save size={13} />
              Save current filters
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>

        <div className="ml-auto text-xs text-muted-foreground">
          {isFetching ? 'Loading…' : `${total} result${total === 1 ? '' : 's'}`}
        </div>
      </div>

      {/* Bulk bar */}
      {selected.size > 0 && (
        <div className="flex items-center gap-3 mb-3 px-3 py-2 rounded-md bg-accent border border-border">
          <span className="text-sm font-medium">
            {selected.size} selected
          </span>
          <button
            onClick={clearSelected}
            className="text-xs text-muted-foreground hover:text-foreground"
          >
            Clear
          </button>
          <div className="h-4 w-px bg-border mx-1" />
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <button className="px-2 py-1 rounded-md text-sm hover:bg-background">
                Reassign
              </button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="start">
              <DropdownMenuItem
                onSelect={() =>
                  setConfirmBulk({
                    kind: 'reassign',
                    value: null,
                    label: 'Unassign',
                  })
                }
              >
                Unassigned
              </DropdownMenuItem>
              {agentUsers.map((u) => (
                <DropdownMenuItem
                  key={u.id}
                  onSelect={() =>
                    setConfirmBulk({
                      kind: 'reassign',
                      value: u.id,
                      label: `Assign to ${u.displayName}`,
                    })
                  }
                >
                  {u.displayName}
                </DropdownMenuItem>
              ))}
            </DropdownMenuContent>
          </DropdownMenu>

          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <button className="px-2 py-1 rounded-md text-sm hover:bg-background">
                Severity
              </button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="start">
              {[1, 2, 3, 4, 5].map((s) => (
                <DropdownMenuItem
                  key={s}
                  onSelect={() =>
                    setConfirmBulk({
                      kind: 'setSeverity',
                      value: s,
                      label: `Set severity SEV ${s}`,
                    })
                  }
                >
                  SEV {s}
                </DropdownMenuItem>
              ))}
            </DropdownMenuContent>
          </DropdownMenu>

          <button
            onClick={() =>
              setConfirmBulk({ kind: 'close', label: 'Close selected tickets' })
            }
            className="px-2 py-1 rounded-md text-sm hover:bg-background"
          >
            Close
          </button>
        </div>
      )}

      {/* Ticket list */}
      {isLoading ? (
        <div className="text-center py-16 text-muted-foreground text-sm">Loading…</div>
      ) : tickets.length === 0 ? (
        <div className="text-center py-16 text-muted-foreground text-sm">No tickets found</div>
      ) : (
        <div className="rounded-md border border-border overflow-hidden">
          <div className="flex items-center gap-3 px-4 py-2 bg-card text-xs text-muted-foreground border-b border-border">
            <input
              type="checkbox"
              checked={allVisible}
              aria-label="Select all on page"
              ref={(el) => {
                if (el) el.indeterminate = !allVisible && someVisible;
              }}
              onChange={toggleAll}
              className="cursor-pointer"
            />
            <span>
              {tickets.length} of {total}
            </span>
          </div>

          <ul className="divide-y divide-border">
            {tickets.map((ticket, idx) => (
              <li
                key={ticket.id}
                className={`flex items-center gap-3 px-4 py-3 transition-colors ${
                  idx === cursor
                    ? 'bg-accent/50 ring-1 ring-inset ring-primary'
                    : 'hover:bg-accent/30'
                }`}
              >
                <input
                  type="checkbox"
                  checked={selected.has(ticket.id)}
                  onChange={() => toggleOne(ticket.id)}
                  aria-label={`Select ${ticket.displayId}`}
                  className="cursor-pointer flex-shrink-0"
                />
                <div
                  className={`w-1 self-stretch rounded-full flex-shrink-0 ${SEVERITY_BG[ticket.severity] ?? 'bg-gray-600'}`}
                />
                <Link
                  to={`/${ticket.displayId}`}
                  className="flex-1 min-w-0 flex items-center gap-3 group"
                >
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-0.5 flex-wrap">
                      <span className="text-sm font-medium text-foreground group-hover:text-primary truncate">
                        {ticket.title}
                      </span>
                      <span className="text-xs font-mono text-muted-foreground">
                        {ticket.displayId}
                      </span>
                    </div>
                    <div className="flex items-center gap-2 text-xs text-muted-foreground flex-wrap">
                      <SeverityBadge severity={ticket.severity} />
                      <StatusBadge status={ticket.status} />
                      <span>
                        opened {formatDistanceToNow(new Date(ticket.createdAt), {
                          addSuffix: true,
                        })}{' '}
                        by {ticket.createdBy.displayName}
                      </span>
                      <span className="hidden md:inline">
                        · {ticket.category.name} › {ticket.type.name} › {ticket.item.name}
                      </span>
                      {ticket.assignee && (
                        <span className="hidden md:inline">· assigned {ticket.assignee.displayName}</span>
                      )}
                      <span>· {ticket._count?.comments ?? 0} comments</span>
                    </div>
                  </div>
                  <div className="hidden sm:flex items-center flex-shrink-0">
                    {ticket.assignee ? (
                      <Avatar name={ticket.assignee.displayName} size="sm" />
                    ) : null}
                  </div>
                </Link>
              </li>
            ))}
          </ul>
        </div>
      )}

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-between mt-4 text-sm">
          <div className="text-muted-foreground">
            Page {page} of {totalPages}
          </div>
          <div className="flex items-center gap-1">
            <button
              disabled={page <= 1}
              onClick={() => updateParam('page', String(page - 1))}
              className="p-1.5 rounded-md hover:bg-accent disabled:opacity-40 disabled:cursor-not-allowed"
            >
              <ChevronLeft size={16} />
            </button>
            <button
              disabled={page >= totalPages}
              onClick={() => updateParam('page', String(page + 1))}
              className="p-1.5 rounded-md hover:bg-accent disabled:opacity-40 disabled:cursor-not-allowed"
            >
              <ChevronRight size={16} />
            </button>
          </div>
        </div>
      )}

      {/* Save view dialog */}
      <Dialog open={saveOpen} onOpenChange={setSaveOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Save current filters</DialogTitle>
          </DialogHeader>
          <div className="py-2">
            <input
              autoFocus
              type="text"
              value={newViewName}
              onChange={(e) => setNewViewName(e.target.value)}
              placeholder="View name"
              className="w-full px-3 py-2 rounded-md border border-input bg-background text-sm focus:outline-none focus:ring-2 focus:ring-ring"
              onKeyDown={(e) => {
                if (e.key === 'Enter') handleSaveView();
              }}
            />
          </div>
          <DialogFooter>
            <button
              onClick={() => setSaveOpen(false)}
              className="px-3 py-1.5 rounded-md border border-input text-sm hover:bg-accent"
            >
              Cancel
            </button>
            <button
              onClick={handleSaveView}
              disabled={!newViewName.trim() || createView.isPending}
              className="px-3 py-1.5 rounded-md bg-primary text-primary-foreground text-sm disabled:opacity-50"
            >
              Save
            </button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Confirm bulk action */}
      <AlertDialog open={!!confirmBulk} onOpenChange={(o) => !o && setConfirmBulk(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{confirmBulk?.label}</AlertDialogTitle>
            <AlertDialogDescription>
              This will affect {selected.size} ticket{selected.size === 1 ? '' : 's'}.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => {
                if (!confirmBulk) return;
                if (confirmBulk.kind === 'close') runBulk({ action: 'close' });
                else
                  runBulk({
                    action: confirmBulk.kind,
                    value: confirmBulk.value,
                  });
              }}
            >
              Confirm
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </Layout>
  );
}
