import { useQuery, useMutation } from "@tanstack/react-query";
import { useParams, Link } from "wouter";
import { format } from "date-fns";
import { ru } from "date-fns/locale";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
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 { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { MessageTimeline } from "@/components/message-timeline";
import { MediaGallery } from "@/components/media-gallery";
import { ReplyForm } from "@/components/reply-form";
import { useToast } from "@/hooks/use-toast";
import { apiRequest, queryClient } from "@/lib/queryClient";
import {
  ArrowLeft,
  User,
  AtSign,
  Hash,
  Calendar,
  CheckCircle,
  Clock,
  AlertCircle,
} from "lucide-react";
import type { SupportRequest, SupportMessage, RequestStatus } from "@shared/schema";

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

export default function RequestDetailPage() {
  const { id } = useParams<{ id: string }>();
  const { toast } = useToast();

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

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

  const { data: history } = useQuery<SupportRequest[]>({
    queryKey: ["/api/users", request?.odID, "requests"],
    enabled: !!request?.odID,
  });

  const replyMutation = useMutation({
    mutationFn: async (message: string) => {
      const response = await apiRequest("POST", `/api/requests/${id}/reply`, { message });
      return response.json();
    },
    onSuccess: () => {
      toast({
        title: "Сообщение отправлено",
        description: "Ответ успешно отправлен пользователю",
      });
      queryClient.invalidateQueries({ queryKey: ["/api/requests", id, "messages"] });
      queryClient.invalidateQueries({ queryKey: ["/api/requests", id] });
    },
    onError: (error: Error) => {
      toast({
        title: "Ошибка отправки",
        description: error.message,
        variant: "destructive",
      });
    },
  });

  const statusMutation = useMutation({
    mutationFn: async (status: RequestStatus) => {
      const response = await apiRequest("PATCH", `/api/requests/${id}/status`, { status });
      return response.json();
    },
    onSuccess: () => {
      toast({
        title: "Статус обновлён",
        description: "Статус обращения успешно изменён",
      });
      queryClient.invalidateQueries({ queryKey: ["/api/requests", id] });
      queryClient.invalidateQueries({ queryKey: ["/api/requests"] });
    },
    onError: (error: Error) => {
      toast({
        title: "Ошибка",
        description: error.message,
        variant: "destructive",
      });
    },
  });

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

  if (requestLoading) {
    return (
      <div className="space-y-6">
        <Skeleton className="h-8 w-48" />
        <div className="grid gap-6 lg:grid-cols-3">
          <div className="lg:col-span-2 space-y-6">
            <Skeleton className="h-64" />
            <Skeleton className="h-48" />
          </div>
          <Skeleton className="h-80" />
        </div>
      </div>
    );
  }

  if (!request) {
    return (
      <div className="flex flex-col items-center justify-center py-16 text-center">
        <h2 className="text-xl font-semibold mb-2">Обращение не найдено</h2>
        <p className="text-muted-foreground mb-4">
          Обращение с ID {id} не существует или было удалено
        </p>
        <Button asChild>
          <Link href="/requests">
            <ArrowLeft className="h-4 w-4 mr-2" />
            К списку обращений
          </Link>
        </Button>
      </div>
    );
  }

  const status = statusConfig[request.status];
  const StatusIcon = status.icon;

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="icon" asChild>
          <Link href="/requests" data-testid="button-back">
            <ArrowLeft className="h-4 w-4" />
          </Link>
        </Button>
        <div className="flex-1">
          <h1 className="text-2xl font-semibold">Обращение #{request.id}</h1>
          <p className="text-muted-foreground">
            от {request.odFirstName} {request.odLastName}
          </p>
        </div>
        <Select
          value={request.status}
          onValueChange={(v) => statusMutation.mutate(v as RequestStatus)}
        >
          <SelectTrigger className="w-[160px]" data-testid="select-request-status">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="new">
              <span className="flex items-center gap-2">
                <AlertCircle className="h-3 w-3" />
                Новое
              </span>
            </SelectItem>
            <SelectItem value="in_progress">
              <span className="flex items-center gap-2">
                <Clock className="h-3 w-3" />
                В работе
              </span>
            </SelectItem>
            <SelectItem value="resolved">
              <span className="flex items-center gap-2">
                <CheckCircle className="h-3 w-3" />
                Решено
              </span>
            </SelectItem>
          </SelectContent>
        </Select>
      </div>

      <div className="grid gap-6 lg:grid-cols-3">
        <div className="lg:col-span-2 space-y-6">
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between gap-2">
                <CardTitle>Обращение</CardTitle>
                <Badge variant={status.variant}>
                  <StatusIcon className="h-3 w-3 mr-1" />
                  {status.label}
                </Badge>
              </div>
              <CardDescription>
                {format(new Date(request.timestamp * 1000), "d MMMM yyyy, HH:mm", { locale: ru })}
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <p className="text-sm whitespace-pre-wrap">{request.text}</p>

              {request.media && (
                <>
                  <Separator />
                  <div>
                    <h4 className="text-sm font-medium mb-3">Прикреплённые файлы</h4>
                    <MediaGallery media={request.media} />
                  </div>
                </>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Ответить</CardTitle>
              <CardDescription>
                Отправить сообщение пользователю в Telegram
              </CardDescription>
            </CardHeader>
            <CardContent>
              <ReplyForm
                onSubmit={(message) => replyMutation.mutate(message)}
                isPending={replyMutation.isPending}
              />
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>История переписки</CardTitle>
              <CardDescription>
                Все сообщения по этому обращению
              </CardDescription>
            </CardHeader>
            <CardContent>
              {messagesLoading ? (
                <div className="space-y-4">
                  {[...Array(3)].map((_, i) => (
                    <Skeleton key={i} className="h-16" />
                  ))}
                </div>
              ) : (
                <MessageTimeline messages={messages || []} />
              )}
            </CardContent>
          </Card>
        </div>

        <div className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Пользователь</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex items-center gap-4">
                <Avatar className="h-16 w-16">
                  <AvatarFallback className="text-lg">
                    {getInitials(request.odFirstName, request.odLastName)}
                  </AvatarFallback>
                </Avatar>
                <div>
                  <h3 className="font-semibold">
                    {request.odFirstName} {request.odLastName}
                  </h3>
                  {request.odUsername && (
                    <p className="text-sm text-muted-foreground">
                      @{request.odUsername}
                    </p>
                  )}
                </div>
              </div>

              <Separator />

              <div className="space-y-3">
                <div className="flex items-center gap-3 text-sm">
                  <Hash className="h-4 w-4 text-muted-foreground" />
                  <span className="text-muted-foreground">ID:</span>
                  <span className="font-mono">{request.odID}</span>
                </div>
                {request.odUsername && (
                  <div className="flex items-center gap-3 text-sm">
                    <AtSign className="h-4 w-4 text-muted-foreground" />
                    <span className="text-muted-foreground">Username:</span>
                    <a
                      href={`https://t.me/${request.odUsername}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-primary hover:underline"
                    >
                      @{request.odUsername}
                    </a>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>История обращений</CardTitle>
              <CardDescription>
                Предыдущие обращения этого пользователя
              </CardDescription>
            </CardHeader>
            <CardContent>
              {history && history.length > 0 ? (
                <div className="space-y-3">
                  {history
                    .filter((h) => h.id !== request.id)
                    .slice(0, 5)
                    .map((h) => (
                      <Link
                        key={h.id}
                        href={`/requests/${h.id}`}
                        className="block p-3 rounded-lg bg-muted hover-elevate"
                      >
                        <div className="flex items-center justify-between gap-2 mb-1">
                          <span className="text-xs font-mono text-muted-foreground">
                            #{h.id}
                          </span>
                          <Badge
                            variant={statusConfig[h.status].variant}
                            className="text-[10px]"
                          >
                            {statusConfig[h.status].label}
                          </Badge>
                        </div>
                        <p className="text-sm truncate">{h.text}</p>
                        <span className="text-xs text-muted-foreground">
                          {format(new Date(h.timestamp * 1000), "d MMM yyyy", { locale: ru })}
                        </span>
                      </Link>
                    ))}
                </div>
              ) : (
                <p className="text-sm text-muted-foreground text-center py-4">
                  Нет предыдущих обращений
                </p>
              )}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
