import { useState, useMemo } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { RequestTable } from "@/components/request-table";
import { StatusFilter } from "@/components/status-filter";
import { BulkReplyDialog } from "@/components/bulk-reply-dialog";
import { useToast } from "@/hooks/use-toast";
import { apiRequest, queryClient } from "@/lib/queryClient";
import type { SupportRequest, RequestStatus } from "@shared/schema";

export default function RequestsPage() {
  const { toast } = useToast();
  const [status, setStatus] = useState<RequestStatus | "all">("all");
  const [search, setSearch] = useState("");
  const [selectedIds, setSelectedIds] = useState<number[]>([]);
  const [bulkDialogOpen, setBulkDialogOpen] = useState(false);

  const { data: requests, isLoading } = useQuery<SupportRequest[]>({
    queryKey: ["/api/requests"],
  });

  const filteredRequests = useMemo(() => {
    if (!requests) return [];

    return requests.filter((request) => {
      const matchesStatus = status === "all" || request.status === status;
      const matchesSearch =
        search === "" ||
        request.odFirstName.toLowerCase().includes(search.toLowerCase()) ||
        request.odLastName.toLowerCase().includes(search.toLowerCase()) ||
        request.odUsername.toLowerCase().includes(search.toLowerCase()) ||
        request.text.toLowerCase().includes(search.toLowerCase());

      return matchesStatus && matchesSearch;
    });
  }, [requests, status, search]);

  const selectedRequests = useMemo(() => {
    return filteredRequests.filter((r) => selectedIds.includes(r.id));
  }, [filteredRequests, selectedIds]);

  const bulkReplyMutation = useMutation({
    mutationFn: async ({ message, requestIds }: { message: string; requestIds: number[] }) => {
      const response = await apiRequest("POST", "/api/requests/bulk-reply", {
        message,
        requestIds,
      });
      return response.json();
    },
    onSuccess: (data) => {
      toast({
        title: "Сообщения отправлены",
        description: `Отправлено ${data.sent} из ${data.total} сообщений`,
      });
      setSelectedIds([]);
      setBulkDialogOpen(false);
      queryClient.invalidateQueries({ queryKey: ["/api/requests"] });
    },
    onError: (error: Error) => {
      toast({
        title: "Ошибка отправки",
        description: error.message,
        variant: "destructive",
      });
    },
  });

  const handleBulkReply = (message: string) => {
    bulkReplyMutation.mutate({
      message,
      requestIds: selectedIds,
    });
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-semibold">Обращения</h1>
        <p className="text-muted-foreground">
          Управление обращениями пользователей
        </p>
      </div>

      <StatusFilter
        status={status}
        onStatusChange={setStatus}
        search={search}
        onSearchChange={setSearch}
      />

      <RequestTable
        requests={filteredRequests}
        isLoading={isLoading}
        selectedIds={selectedIds}
        onSelectionChange={setSelectedIds}
        onBulkReply={() => setBulkDialogOpen(true)}
      />

      <BulkReplyDialog
        open={bulkDialogOpen}
        onOpenChange={setBulkDialogOpen}
        selectedRequests={selectedRequests}
        onSubmit={handleBulkReply}
        isPending={bulkReplyMutation.isPending}
      />
    </div>
  );
}
