import { useState } from "react";
import { Link } from "wouter";
import { format } from "date-fns";
import { ru } from "date-fns/locale";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Checkbox } from "@/components/ui/checkbox";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Skeleton } from "@/components/ui/skeleton";
import {
  Image,
  Video,
  ExternalLink,
  Send,
} from "lucide-react";
import type { SupportRequest, RequestStatus } from "@shared/schema";

interface RequestTableProps {
  requests: SupportRequest[];
  isLoading: boolean;
  selectedIds: number[];
  onSelectionChange: (ids: number[]) => void;
  onBulkReply: () => void;
}

const statusConfig: Record<
  RequestStatus,
  { label: string; variant: "default" | "secondary" | "outline" }
> = {
  new: { label: "Новое", variant: "default" },
  in_progress: { label: "В работе", variant: "secondary" },
  resolved: { label: "Решено", variant: "outline" },
};

export function RequestTable({
  requests,
  isLoading,
  selectedIds,
  onSelectionChange,
  onBulkReply,
}: RequestTableProps) {
  const allSelected =
    requests.length > 0 && selectedIds.length === requests.length;
  const someSelected = selectedIds.length > 0 && !allSelected;

  const toggleAll = () => {
    if (allSelected) {
      onSelectionChange([]);
    } else {
      onSelectionChange(requests.map((r) => r.id));
    }
  };

  const toggleOne = (id: number) => {
    if (selectedIds.includes(id)) {
      onSelectionChange(selectedIds.filter((i) => i !== id));
    } else {
      onSelectionChange([...selectedIds, id]);
    }
  };

  const getInitials = (firstName: string, lastName: string) => {
    return `${firstName.charAt(0)}${lastName.charAt(0) || ""}`.toUpperCase();
  };

  const hasMedia = (media: string | null) => {
    if (!media) return null;
    if (media.includes("video") || media.endsWith(".mp4")) return "video";
    return "image";
  };

  if (isLoading) {
    return (
      <div className="space-y-4">
        {[...Array(5)].map((_, i) => (
          <Skeleton key={i} className="h-16 w-full" />
        ))}
      </div>
    );
  }

  if (requests.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center py-16 text-center">
        <div className="rounded-full bg-muted p-4 mb-4">
          <Send className="h-8 w-8 text-muted-foreground" />
        </div>
        <h3 className="text-lg font-semibold mb-2">Нет обращений</h3>
        <p className="text-sm text-muted-foreground">
          Обращения от пользователей появятся здесь
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {selectedIds.length > 0 && (
        <div className="flex items-center justify-between gap-4 p-4 bg-muted rounded-lg">
          <span className="text-sm font-medium">
            Выбрано: {selectedIds.length}
          </span>
          <Button onClick={onBulkReply} data-testid="button-bulk-reply">
            <Send className="h-4 w-4 mr-2" />
            Массовый ответ
          </Button>
        </div>
      )}
      <div className="rounded-lg border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-12">
                <Checkbox
                  checked={allSelected}
                  ref={(el) => {
                    if (el) {
                      (el as HTMLButtonElement & { indeterminate?: boolean }).indeterminate = someSelected;
                    }
                  }}
                  onCheckedChange={toggleAll}
                  data-testid="checkbox-select-all"
                />
              </TableHead>
              <TableHead>Статус</TableHead>
              <TableHead>Пользователь</TableHead>
              <TableHead className="max-w-[300px]">Сообщение</TableHead>
              <TableHead>Дата</TableHead>
              <TableHead className="w-12">Медиа</TableHead>
              <TableHead className="w-12"></TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {requests.map((request) => {
              const mediaType = hasMedia(request.media);
              const status = statusConfig[request.status];

              return (
                <TableRow
                  key={request.id}
                  className="hover-elevate"
                  data-testid={`row-request-${request.id}`}
                >
                  <TableCell>
                    <Checkbox
                      checked={selectedIds.includes(request.id)}
                      onCheckedChange={() => toggleOne(request.id)}
                      data-testid={`checkbox-request-${request.id}`}
                    />
                  </TableCell>
                  <TableCell>
                    <Badge variant={status.variant} className="text-xs">
                      {status.label}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-3">
                      <Avatar className="h-8 w-8">
                        <AvatarFallback className="text-xs">
                          {getInitials(request.odFirstName, request.odLastName)}
                        </AvatarFallback>
                      </Avatar>
                      <div className="flex flex-col">
                        <span className="text-sm font-medium">
                          {request.odFirstName} {request.odLastName}
                        </span>
                        {request.odUsername && (
                          <span className="text-xs text-muted-foreground">
                            @{request.odUsername}
                          </span>
                        )}
                      </div>
                    </div>
                  </TableCell>
                  <TableCell className="max-w-[300px]">
                    <p className="text-sm truncate">{request.text}</p>
                  </TableCell>
                  <TableCell>
                    <span className="text-xs text-muted-foreground font-mono">
                      {format(new Date(request.timestamp * 1000), "dd MMM yyyy HH:mm", {
                        locale: ru,
                      })}
                    </span>
                  </TableCell>
                  <TableCell>
                    {mediaType === "video" && (
                      <Video className="h-4 w-4 text-muted-foreground" />
                    )}
                    {mediaType === "image" && (
                      <Image className="h-4 w-4 text-muted-foreground" />
                    )}
                  </TableCell>
                  <TableCell>
                    <Button variant="ghost" size="icon" asChild>
                      <Link
                        href={`/requests/${request.id}`}
                        data-testid={`link-request-${request.id}`}
                      >
                        <ExternalLink className="h-4 w-4" />
                      </Link>
                    </Button>
                  </TableCell>
                </TableRow>
              );
            })}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}
