import {
  type ReactNode,
  useCallback,
  useEffect,
  useRef,
  useState,
} from 'react';
import { router, usePage } from '@inertiajs/react';
import {
  ArrowLeft,
  Check,
  CheckCheck,
  LoaderCircle,
  MessageCircleMore,
  Paperclip,
  Plus,
  RefreshCw,
  Send,
  X,
} from 'lucide-react';
import { useForm } from 'react-hook-form';
import { Button } from '@rutatiina/ui/components/ui/button';
import { Input } from '@rutatiina/ui/components/ui/input';
import { Textarea } from '@rutatiina/ui/components/ui/textarea';
import {
  Sheet,
  SheetBody,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
} from '@rutatiina/ui/components/ui/sheet';
import { UserAvatar } from '@rutatiina/ui/components/common/user-avatar';
import { useInertiaForm } from '@rutatiina/ui/hooks/use-inertia-form';
import { useHasModule } from '@rutatiina/ui/hooks/use-modules';
import { useRealtime } from '@rutatiina/ui/lib/realtime';
import { cn } from '@rutatiina/ui/lib/utils';
import { messagingRequest } from '@rutatiina/messaging/request';
import type {
  Conversation,
  ListResponse,
  Message,
  MessagingUser,
  ThreadResponse,
} from '@rutatiina/messaging/types';

export function MessagingSheet({ trigger }: { trigger: ReactNode }) {
  const { messaging } = usePage().props;
  if (!messaging.enabled) return null;
  return <EnabledMessagingSheet trigger={trigger} />;
}

function EnabledMessagingSheet({ trigger }: { trigger: ReactNode }) {
  const [open, setOpen] = useState(false);
  const [newMessage, setNewMessage] = useState(false);
  const [peer, setPeer] = useState<MessagingUser | null>(null);
  return (
    <Sheet open={open} onOpenChange={setOpen}>
      <SheetTrigger asChild>{trigger}</SheetTrigger>
      <SheetContent className="inset-5 start-auto h-auto w-[calc(100%-2.5rem)] gap-0 rounded-lg p-0 sm:w-[450px] sm:max-w-none [&_[data-slot=sheet-close]]:end-5 [&_[data-slot=sheet-close]]:top-4.5">
        <SheetHeader className="border-border border-b p-3">
          <SheetTitle>Messages</SheetTitle>
          <SheetDescription className="sr-only">
            Private conversations with other users.
          </SheetDescription>
        </SheetHeader>
        <SheetBody className="flex min-h-0 flex-1 flex-col p-0">
          {open &&
            (peer ? (
              <ConversationThread
                peer={peer}
                onBack={() => {
                  setPeer(null);
                  setNewMessage(false);
                }}
              />
            ) : (
              <ConversationList
                newMessage={newMessage}
                onNewMessage={() => setNewMessage(true)}
                onBack={() => setNewMessage(false)}
                onSelect={setPeer}
              />
            ))}
        </SheetBody>
      </SheetContent>
    </Sheet>
  );
}

function Failure({ message, retry }: { message: string; retry: () => void }) {
  return (
    <div
      role="alert"
      className="text-muted-foreground flex flex-col items-center gap-3 p-5 text-center text-sm"
    >
      <p>{message}</p>
      <Button size="sm" variant="outline" onClick={retry}>
        Try again
      </Button>
    </div>
  );
}

function ConversationList({
  newMessage,
  onNewMessage,
  onBack,
  onSelect,
}: {
  newMessage: boolean;
  onNewMessage: () => void;
  onBack: () => void;
  onSelect: (user: MessagingUser) => void;
}) {
  const { messaging } = usePage().props;
  const [query, setQuery] = useState('');
  const [items, setItems] = useState<(Conversation | MessagingUser)[]>([]);
  const [nextPage, setNextPage] = useState<number | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [refresh, setRefresh] = useState(0);
  const version = useRef(0);
  const load = useCallback(
    async (page: number, signal?: AbortSignal) => {
      const requestVersion = ++version.current;
      setLoading(true);
      setError('');
      try {
        const url = newMessage
          ? `/messages/recipients?q=${encodeURIComponent(query)}&page=${page}`
          : `/messages?page=${page}`;
        const response = await messagingRequest<
          ListResponse<Conversation | MessagingUser>
        >(url, { signal });
        if (requestVersion !== version.current || signal?.aborted) return;
        setItems((existing) =>
          page === 1 ? response.data : [...existing, ...response.data],
        );
        setNextPage(response.next_page);
      } catch (error) {
        if (requestVersion === version.current && !signal?.aborted)
          setError(
            error instanceof Error ? error.message : 'Could not load messages.',
          );
      } finally {
        if (requestVersion === version.current && !signal?.aborted)
          setLoading(false);
      }
    },
    [newMessage, query],
  );
  useEffect(() => {
    const controller = new AbortController();
    setItems([]);
    setNextPage(null);
    setLoading(true);
    const timer = window.setTimeout(
      () => {
        void load(1, controller.signal);
      },
      newMessage ? 250 : 0,
    );
    return () => {
      window.clearTimeout(timer);
      controller.abort();
      version.current++;
    };
  }, [load, newMessage, refresh, messaging.unread]);

  return (
    <>
      <div className="border-border flex items-center gap-2 border-b p-3">
        {newMessage ? (
          <>
            <Button
              variant="ghost"
              mode="icon"
              aria-label="Back to conversations"
              onClick={onBack}
            >
              <ArrowLeft className="size-4" />
            </Button>
            <Input
              autoFocus
              value={query}
              onChange={(event) => setQuery(event.target.value)}
              maxLength={100}
              placeholder="Search users by name or email"
              aria-label="Search recipients"
            />
          </>
        ) : (
          <>
            <span className="grow text-sm font-medium">Your conversations</span>
            <Button
              variant="ghost"
              mode="icon"
              aria-label="Refresh conversations"
              disabled={loading}
              onClick={() => setRefresh((value) => value + 1)}
            >
              <RefreshCw className="size-4" />
            </Button>
            <Button variant="outline" size="sm" onClick={onNewMessage}>
              <Plus className="size-4" />
              New message
            </Button>
          </>
        )}
      </div>
      <div className="min-h-0 flex-1 overflow-y-auto" aria-busy={loading}>
        {error ? (
          <Failure
            message={error}
            retry={() => {
              void load(items.length ? (nextPage ?? 1) : 1);
            }}
          />
        ) : null}
        {loading && items.length === 0 ? (
          <div role="status" className="flex justify-center p-8">
            <LoaderCircle className="size-5 animate-spin" />
            <span className="sr-only">Loading conversations</span>
          </div>
        ) : null}
        {!loading && !error && items.length === 0 ? (
          <div
            role="status"
            className="flex flex-col items-center gap-2 p-8 text-center"
          >
            <MessageCircleMore className="text-muted-foreground size-8" />
            <p className="text-sm font-medium">
              {newMessage ? 'No users found' : 'No conversations yet'}
            </p>
            <p className="text-muted-foreground text-xs">
              {newMessage
                ? 'Try another name or email.'
                : 'Choose New message to start a conversation.'}
            </p>
          </div>
        ) : null}
        {items.map((item) => {
          const conversation = 'user' in item ? item : null;
          const user = conversation
            ? conversation.user
            : (item as MessagingUser);
          return (
            <button
              key={user.id}
              type="button"
              onClick={() => onSelect(user)}
              className="border-border hover:bg-accent focus-visible:ring-ring flex w-full items-start gap-3 border-b p-4 text-start transition-colors focus-visible:ring-2 focus-visible:outline-none focus-visible:ring-inset"
            >
              <UserAvatar
                name={user.name}
                src={user.avatar_url}
                initials={user.initials}
                className="size-9"
              />
              <span className="min-w-0 flex-1">
                <span className="block text-sm font-semibold">{user.name}</span>
                {conversation && (
                  <>
                    <span className="text-muted-foreground block truncate text-xs">
                      {conversation.last_message.body ||
                        (conversation.last_message.attachment &&
                          `📎 ${conversation.last_message.attachment.name}`)}
                    </span>
                    <time
                      className="text-muted-foreground text-xs"
                      dateTime={conversation.last_message.created_at}
                    >
                      {new Date(
                        conversation.last_message.created_at,
                      ).toLocaleString()}
                    </time>
                  </>
                )}
                {!user.active && (
                  <span className="text-muted-foreground block text-xs">
                    This user is unavailable
                  </span>
                )}
              </span>
              {conversation && conversation.unread > 0 && (
                <span
                  className="bg-primary text-primary-foreground rounded-full px-2 text-xs leading-5"
                  aria-label={`${conversation.unread} unread messages`}
                >
                  {conversation.unread}
                </span>
              )}
            </button>
          );
        })}
        {nextPage && !error ? (
          <div className="p-3 text-center">
            <Button
              variant="outline"
              size="sm"
              disabled={loading}
              onClick={() => {
                void load(nextPage);
              }}
            >
              Load more
            </Button>
          </div>
        ) : null}
      </div>
    </>
  );
}

function ConversationThread({
  peer,
  onBack,
}: {
  peer: MessagingUser;
  onBack: () => void;
}) {
  'use no memo';
  const { auth } = usePage().props;
  const [user, setUser] = useState(peer);
  const [messages, setMessages] = useState<Message[]>([]);
  const [before, setBefore] = useState<number | null>(null);
  const [loading, setLoading] = useState(true);
  const [loadingOlder, setLoadingOlder] = useState(false);
  const [error, setError] = useState('');
  const [refresh, setRefresh] = useState(0);
  // New messages from this person, and their reading ours, arrive at once while live.
  const live = useRealtime<{ user_id: number | string }>(
    ['messages.received', 'messages.read'],
    (payload) => {
      if (Number(payload.user_id) === peer.id) setRefresh((value) => value + 1);
    },
  );
  const bottomRef = useRef<HTMLDivElement>(null);
  const scroller = useRef<HTMLDivElement>(null);
  const nearBottom = useRef(true);
  const lastId = useRef(0);
  const initialized = useRef(false);
  const clientId = useRef<string | null>(null);
  const mounted = useRef(true);
  const form = useForm<{ body: string; recipient_id?: number }>({
    defaultValues: { body: '' },
  });
  const { submit, processing } = useInertiaForm(form, {
    recipient_id: 'root',
    attachment: 'root',
  });
  // Files are sent through the media library, so only while rutatiina/media is installed.
  const canAttach = useHasModule('media');
  const [attachment, setAttachment] = useState<File | null>(null);
  const fileInput = useRef<HTMLInputElement>(null);

  useEffect(() => {
    const controller = new AbortController();
    mounted.current = true;
    let fetching = false;
    const load = async () => {
      if (fetching) return;
      fetching = true;
      try {
        const response = await messagingRequest<ThreadResponse>(
          `/messages/with/${peer.id}`,
          { signal: controller.signal },
        );
        if (controller.signal.aborted) return;
        setUser(response.user);
        setMessages((existing) =>
          [
            ...new Map(
              [...existing, ...response.data].map((message) => [
                message.id,
                message,
              ]),
            ).values(),
          ].sort((a, b) => a.id - b.id),
        );
        if (!initialized.current) {
          setBefore(response.next_before);
          initialized.current = true;
        }
        setError('');
        const newest = response.data.at(-1)?.id ?? 0;
        if (newest !== lastId.current) {
          lastId.current = newest;
          if (nearBottom.current)
            window.requestAnimationFrame(() =>
              bottomRef.current?.scrollIntoView({ block: 'end' }),
            );
        }
        if (newest > 0 && document.visibilityState === 'visible') {
          const result = await messagingRequest<{ changed: boolean }>(
            `/messages/with/${peer.id}/read`,
            {
              method: 'POST',
              body: JSON.stringify({ up_to: newest }),
              signal: controller.signal,
            },
          );
          if (result.changed && !controller.signal.aborted) {
            setMessages((existing) =>
              existing.map((message) =>
                message.sender_id === peer.id && !message.read_at
                  ? { ...message, read_at: new Date().toISOString() }
                  : message,
              ),
            );
            router.reload({ only: ['messaging'] });
          }
        }
      } catch (error) {
        if (!controller.signal.aborted)
          setError(
            error instanceof Error ? error.message : 'Could not load messages.',
          );
      } finally {
        if (!controller.signal.aborted) setLoading(false);
        fetching = false;
      }
    };
    void load();
    const timer = live
      ? undefined
      : window.setInterval(() => {
          if (document.visibilityState === 'visible') void load();
        }, 5000);
    return () => {
      mounted.current = false;
      controller.abort();
      window.clearInterval(timer);
    };
  }, [peer.id, refresh, live]);

  const loadOlder = async () => {
    if (!before) return;
    setLoadingOlder(true);
    const element = scroller.current;
    const height = element?.scrollHeight ?? 0;
    try {
      const response = await messagingRequest<ThreadResponse>(
        `/messages/with/${peer.id}?before=${before}`,
      );
      if (!mounted.current) return;
      setMessages((existing) =>
        [
          ...new Map(
            [...response.data, ...existing].map((message) => [
              message.id,
              message,
            ]),
          ).values(),
        ].sort((a, b) => a.id - b.id),
      );
      setBefore(response.next_before);
      setError('');
      window.requestAnimationFrame(() => {
        if (element) element.scrollTop += element.scrollHeight - height;
      });
    } catch (error) {
      if (mounted.current)
        setError(
          error instanceof Error ? error.message : 'Could not load messages.',
        );
    } finally {
      if (mounted.current) setLoadingOlder(false);
    }
  };

  const send = form.handleSubmit(({ body }) => {
    if (processing || (!body.trim() && !attachment) || !user.active) return;
    clientId.current ??= crypto.randomUUID();
    submit(
      'post',
      '/messages',
      {
        recipient_id: peer.id,
        body,
        client_id: clientId.current,
        ...(attachment ? { attachment } : {}),
      },
      {
        only: ['messaging'],
        forceFormData: Boolean(attachment),
        onSuccess: () => {
          form.reset({ body: '' });
          setAttachment(null);
          clientId.current = null;
          nearBottom.current = true;
          setRefresh((value) => value + 1);
        },
        onHttpException: () => {
          form.setError('root', {
            message: 'Could not send your message. Please try again.',
          });
          router.reload({ only: ['messaging'] });
          return false;
        },
        onNetworkError: () => {
          form.setError('root', {
            message: 'Could not send your message. Please try again.',
          });
          return false;
        },
      },
    );
  });

  return (
    <>
      <div className="border-border flex items-center gap-3 border-b p-3">
        <Button
          variant="ghost"
          mode="icon"
          aria-label="Back to conversations"
          disabled={processing}
          onClick={onBack}
        >
          <ArrowLeft className="size-4" />
        </Button>
        <UserAvatar
          name={user.name}
          src={user.avatar_url}
          initials={user.initials}
          className="size-9"
        />
        <div className="min-w-0">
          <p className="truncate text-sm font-semibold">{user.name}</p>
          <p className="text-muted-foreground text-xs">Private conversation</p>
        </div>
      </div>
      <div
        ref={scroller}
        className="min-h-0 flex-1 space-y-3.5 overflow-y-auto p-4"
        aria-busy={loading || loadingOlder}
        onScroll={() => {
          const element = scroller.current;
          if (element)
            nearBottom.current =
              element.scrollHeight - element.scrollTop - element.clientHeight <
              100;
        }}
      >
        {error && (
          <Failure
            message={error}
            retry={() => setRefresh((value) => value + 1)}
          />
        )}
        {loading ? (
          <div role="status" className="flex justify-center p-5">
            <LoaderCircle className="size-5 animate-spin" />
            <span className="sr-only">Loading messages</span>
          </div>
        ) : null}
        {before && (
          <div className="text-center">
            <Button
              size="sm"
              variant="outline"
              disabled={loadingOlder}
              onClick={() => {
                void loadOlder();
              }}
            >
              Load older messages
            </Button>
          </div>
        )}
        {!loading && !error && messages.length === 0 && (
          <p
            role="status"
            className="text-muted-foreground py-5 text-center text-sm"
          >
            Start your conversation with {user.name}.
          </p>
        )}
        {messages.map((message) => {
          const outgoing = message.sender_id === auth.user?.id;
          return (
            <div
              key={message.id}
              className={cn('flex', outgoing ? 'justify-end' : 'justify-start')}
            >
              <div className="max-w-[85%] space-y-1">
                {message.attachment && (
                  <a
                    href={message.attachment.url}
                    target="_blank"
                    rel="noreferrer"
                    className={cn(
                      'border-border flex items-center gap-2 overflow-hidden rounded-lg border text-sm',
                      message.attachment.thumb_url ? 'p-0' : 'p-2.5',
                    )}
                  >
                    {message.attachment.thumb_url ? (
                      <img
                        src={message.attachment.thumb_url}
                        alt={message.attachment.name}
                        className="max-h-48 w-full object-cover"
                      />
                    ) : (
                      <>
                        <Paperclip className="text-muted-foreground size-4 shrink-0" />
                        <span className="truncate">
                          {message.attachment.name}
                        </span>
                      </>
                    )}
                  </a>
                )}
                {message.body && (
                  <p
                    className={cn(
                      'rounded-lg p-3 text-sm break-words whitespace-pre-wrap',
                      outgoing
                        ? 'bg-primary text-primary-foreground'
                        : 'bg-accent/60 text-secondary-foreground',
                    )}
                  >
                    {message.body}
                  </p>
                )}
                <div
                  className={cn(
                    'text-muted-foreground flex items-center gap-1 text-xs',
                    outgoing && 'justify-end',
                  )}
                >
                  <time dateTime={message.created_at}>
                    {new Date(message.created_at).toLocaleString()}
                  </time>
                  {outgoing &&
                    (message.read_at ? (
                      <CheckCheck
                        aria-label="Read"
                        className="size-4 text-green-500"
                      />
                    ) : (
                      <Check aria-label="Sent" className="size-4" />
                    ))}
                </div>
              </div>
            </div>
          );
        })}
        <div ref={bottomRef} />
      </div>
      <form
        onSubmit={send}
        className="border-border shrink-0 space-y-2 border-t p-4"
      >
        {!user.active && (
          <p role="status" className="text-muted-foreground text-sm">
            This user is unavailable. You can still view your conversation.
          </p>
        )}
        {(form.formState.errors.body || form.formState.errors.root) && (
          <p role="alert" className="text-destructive text-sm">
            {form.formState.errors.body?.message ||
              form.formState.errors.root?.message}
          </p>
        )}
        {attachment && (
          <div className="bg-accent/60 flex items-center gap-2 rounded-md px-2.5 py-1.5 text-sm">
            <Paperclip className="text-muted-foreground size-4 shrink-0" />
            <span className="min-w-0 grow truncate">{attachment.name}</span>
            <button
              type="button"
              aria-label={`Remove ${attachment.name}`}
              onClick={() => setAttachment(null)}
            >
              <X className="size-4" />
            </button>
          </div>
        )}
        <div className="flex items-end gap-2">
          {canAttach && (
            <>
              <Button
                type="button"
                variant="outline"
                mode="icon"
                aria-label="Attach a file"
                disabled={processing || !user.active || loading}
                onClick={() => fileInput.current?.click()}
              >
                <Paperclip className="size-4" />
              </Button>
              <input
                ref={fileInput}
                type="file"
                hidden
                onChange={(event) => {
                  setAttachment(event.target.files?.[0] ?? null);
                  clientId.current = null;
                  form.clearErrors();
                  event.target.value = '';
                }}
              />
            </>
          )}
          <Textarea
            {...form.register('body', {
              validate: (value) =>
                Boolean(value.trim()) ||
                Boolean(attachment) ||
                'Enter a message.',
              maxLength: {
                value: 5000,
                message: 'Messages must be 5000 characters or fewer.',
              },
              onChange: () => {
                clientId.current = null;
                form.clearErrors();
              },
            })}
            maxLength={5000}
            rows={2}
            disabled={processing || !user.active || loading}
            aria-label="Message"
            aria-invalid={Boolean(form.formState.errors.body)}
            placeholder="Write a message..."
            className="max-h-40 min-h-20 resize-none"
            onKeyDown={(event) => {
              if (
                event.key === 'Enter' &&
                !event.shiftKey &&
                !event.nativeEvent.isComposing
              ) {
                event.preventDefault();
                void send();
              }
            }}
          />
          <Button
            type="submit"
            variant="mono"
            disabled={
              processing ||
              !user.active ||
              loading ||
              (!form.watch('body').trim() && !attachment)
            }
          >
            <Send className="size-4" />
            {processing ? 'Sending...' : 'Send'}
          </Button>
        </div>
        <p className="text-muted-foreground text-xs">
          Enter to send · Shift+Enter for a new line
        </p>
      </form>
    </>
  );
}
