"use client";

import { useState, useRef, useEffect, useCallback } from "react";
import { motion, AnimatePresence } from "framer-motion";
import BoldIcon from "@/components/ui/BoldIcon";
import AttachmentMenu, { AttachmentType } from "./AttachmentMenu";
import TimedMessagePicker from "./TimedMessagePicker";
import ViewOnceToggle from "./ViewOnceToggle";
import ChatBoldIcon from "./ChatBoldIcon";
import { formatTimedLabel } from "@/lib/chat/timedMessages";
import { viewOnceLabel } from "@/lib/chat/viewOnce";

interface MessageInputProps {
  newMessage: string;
  setNewMessage: React.Dispatch<React.SetStateAction<string>>;
  sendMessage: () => void;
  handleFileSelection: (e: React.ChangeEvent<HTMLInputElement>) => void;
  handleVoiceUpload: (blob: Blob) => void;
  onLocationShare?: () => void;
  onTyping?: () => void;
  /** Chat thread: tab bar hidden — less bottom offset */
  isChatThread?: boolean;
  blocked_you?: boolean | undefined;
  replyingTo?: unknown;
  onCancelReply?: () => void;
  replyLabel?: string;
  selfDestructSeconds?: number | null;
  onSelfDestructChange?: (seconds: number | null) => void;
  viewOnceMedia?: boolean;
  onViewOnceChange?: (value: boolean) => void;
}

const formatTime = (seconds: number) => {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
};

const MessageInput = ({
  newMessage,
  setNewMessage,
  sendMessage,
  handleFileSelection,
  handleVoiceUpload,
  onLocationShare,
  onTyping,
  isChatThread = false,
  blocked_you,
  onCancelReply,
  replyLabel,
  selfDestructSeconds = null,
  onSelfDestructChange,
  viewOnceMedia = false,
  onViewOnceChange,
}: MessageInputProps) => {
  const [isRecording, setIsRecording] = useState(false);
  const [recordingTime, setRecordingTime] = useState(0);
  const [menuOpen, setMenuOpen] = useState(false);
  const mediaRecorderRef = useRef<MediaRecorder | null>(null);
  const audioChunksRef = useRef<Blob[]>([]);
  const timerRef = useRef<NodeJS.Timeout | null>(null);
  const streamRef = useRef<MediaStream | null>(null);
  const attachBtnRef = useRef<HTMLButtonElement>(null);
  const imageInputRef = useRef<HTMLInputElement>(null);
  const videoInputRef = useRef<HTMLInputElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const hasText = newMessage.trim().length > 0;
  const showSend = hasText && !isRecording;
  // ردیف تایمر/یک‌بارمصرف فقط هنگام ضبط ویس (برای عکس داخل پیش‌نمایش نمایش داده می‌شود)
  const showMediaOptions = isChatThread && isRecording;

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const MAX_SIZE = 200 * 1024 * 1024;
      if (file.size > MAX_SIZE) {
        alert("حجم فایل نباید بیشتر از 200 مگابایت باشد.");
        return;
      }
    }
    handleFileSelection(e);
    e.target.value = "";
  };

  useEffect(() => {
    if (isRecording) {
      timerRef.current = setInterval(() => {
        setRecordingTime((prev) => prev + 1);
      }, 1000);
    } else {
      if (timerRef.current) clearInterval(timerRef.current);
      setRecordingTime(0);
    }
    return () => {
      if (timerRef.current) clearInterval(timerRef.current);
    };
  }, [isRecording]);

  const stopRecording = useCallback(
    (shouldSend: boolean) => {
      if (mediaRecorderRef.current?.state === "recording") {
        mediaRecorderRef.current.stop();
      }
      setIsRecording(false);
      if (!shouldSend) {
        audioChunksRef.current = [];
      }
      streamRef.current?.getTracks().forEach((t) => t.stop());
      streamRef.current = null;
    },
    []
  );

  const startRecording = async () => {
    if (blocked_you) return;
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      streamRef.current = stream;
      const mediaRecorder = new MediaRecorder(stream);
      mediaRecorderRef.current = mediaRecorder;
      audioChunksRef.current = [];

      mediaRecorder.ondataavailable = (event) => {
        audioChunksRef.current.push(event.data);
      };

      mediaRecorder.onstop = () => {
        if (audioChunksRef.current.length > 0) {
          const audioBlob = new Blob(audioChunksRef.current, {
            type: "audio/webm",
          });
          handleVoiceUpload(audioBlob);
        }
        audioChunksRef.current = [];
      };

      mediaRecorder.start();
      setIsRecording(true);
    } catch {
      alert("دسترسی به میکروفون داده نشد.");
    }
  };

  const handleMicPointerDown = () => {
    if (!hasText && !blocked_you) startRecording();
  };

  const handleMicPointerUp = () => {
    if (isRecording) stopRecording(true);
  };

  const handleAttachmentSelect = (type: AttachmentType) => {
    switch (type) {
      case "image":
      case "camera":
        imageInputRef.current?.click();
        break;
      case "video":
        videoInputRef.current?.click();
        break;
      case "file":
        fileInputRef.current?.click();
        break;
      case "location":
        onLocationShare?.();
        break;
    }
  };

  return (
    <div
      className={`pointer-events-none fixed left-0 right-0 z-50 flex flex-col items-center bg-transparent px-3 sm:px-4 ${
        isChatThread ? "bottom-0 chat-input-area--thread" : "bottom-[5.5rem] chat-input-area"
      }`}
    >
      {(replyLabel ||
        showMediaOptions ||
        (selfDestructSeconds != null && isChatThread) ||
        (viewOnceMedia && isChatThread)) && (
        <div className="pointer-events-auto relative z-[2] mb-2 flex w-full max-w-lg flex-col gap-2">
          {showMediaOptions && (
            <div className="glass-panel flex items-center justify-between gap-2 rounded-2xl px-3 py-2 shadow-lg">
              <span className="text-[11px] font-medium text-neutral-500 dark:text-neutral-400">
                گزینه‌های ارسال مدیا
              </span>
              <div className="flex items-center gap-1.5">
                {onSelfDestructChange && (
                  <TimedMessagePicker
                    value={selfDestructSeconds}
                    onChange={onSelfDestructChange}
                    disabled={blocked_you}
                  />
                )}
                {onViewOnceChange && (
                  <ViewOnceToggle
                    value={viewOnceMedia}
                    onChange={onViewOnceChange}
                    disabled={blocked_you}
                  />
                )}
              </div>
            </div>
          )}
          {replyLabel && (
            <div className="glass-panel flex items-center gap-2 rounded-2xl px-3 py-2.5 text-xs shadow-lg">
              <span className="flex-1 truncate text-neutral-700 dark:text-neutral-200">
                {replyLabel}
              </span>
              <button
                type="button"
                onClick={onCancelReply}
                className="shrink-0 text-[#0095f6]"
              >
                ×
              </button>
            </div>
          )}
          {selfDestructSeconds != null && isChatThread && (
            <div className="chat-timer-glass chat-timer-glass--active flex items-center gap-2 rounded-2xl px-3 py-1.5 text-[11px]">
              <ChatBoldIcon name="timer" size={14} className="shrink-0" />
              <span>
                پیام زماندار — حذف خودکار بعد از{" "}
                {formatTimedLabel(selfDestructSeconds)}
              </span>
            </div>
          )}
          {viewOnceMedia && isChatThread && (
            <div className="chat-timer-glass chat-timer-glass--active flex items-center gap-2 rounded-2xl px-3 py-1.5 text-[11px] text-[#ff9500]">
              <span className="font-semibold">۱</span>
              <span>
                {viewOnceLabel("image")} — گیرنده فقط یک‌بار می‌تواند ببیند
              </span>
            </div>
          )}
        </div>
      )}
      <div
        dir="ltr"
        className="pointer-events-auto relative z-[1] flex w-full max-w-lg items-end gap-2 sm:gap-2.5"
      >
        <div className="relative flex shrink-0 items-center gap-1.5">
          <button
            ref={attachBtnRef}
            type="button"
            disabled={blocked_you || isRecording}
            onClick={() => setMenuOpen((o) => !o)}
            className="chat-action-btn gentle-transition flex h-11 w-11 shrink-0 items-center justify-center rounded-full active:scale-90 disabled:opacity-40"
            aria-label="پیوست"
          >
            <ChatBoldIcon name="attachment" size={22} />
          </button>
          <AttachmentMenu
            open={menuOpen}
            onClose={() => setMenuOpen(false)}
            onSelect={handleAttachmentSelect}
            anchorRef={attachBtnRef}
          />
        </div>

        {/* Glass input box */}
        <div className="glass-chat-input gentle-transition flex min-h-11 flex-1 items-center rounded-[22px] px-4 py-2">
          <input
            ref={imageInputRef}
            type="file"
            accept="image/*"
            multiple
            className="hidden"
            onChange={handleFileChange}
            disabled={blocked_you}
          />
          <input
            ref={videoInputRef}
            type="file"
            accept="video/*"
            className="hidden"
            onChange={handleFileChange}
            disabled={blocked_you}
          />
          <input
            ref={fileInputRef}
            type="file"
            className="hidden"
            onChange={handleFileChange}
            disabled={blocked_you}
          />

          {isRecording ? (
            <div className="flex w-full items-center justify-between gap-2 text-red-500">
              <div className="flex items-center gap-2">
                <span className="relative flex h-2 w-2">
                  <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-red-400 opacity-75" />
                  <span className="relative inline-flex h-2 w-2 rounded-full bg-red-500" />
                </span>
                <span className="font-mono text-xs font-bold">
                  {formatTime(recordingTime)}
                </span>
              </div>
              <button
                type="button"
                onClick={() => stopRecording(false)}
                className="rounded-full p-1"
              >
                <BoldIcon name="stop" size={18} tinted className="text-current" />
              </button>
            </div>
          ) : (
            <textarea
              rows={1}
              placeholder={
                blocked_you ? "امکان ارسال پیام وجود ندارد" : "پیام"
              }
              value={newMessage}
              onChange={(e) => {
                setNewMessage(e.target.value);
                onTyping?.();
              }}
              onKeyDown={(e) => {
                if (e.key === "Enter" && !e.shiftKey) {
                  e.preventDefault();
                  if (hasText) sendMessage();
                }
              }}
              disabled={blocked_you}
              className="max-h-28 min-h-[24px] flex-1 resize-none bg-transparent text-[15px] outline-none placeholder:text-neutral-400 dark:text-white"
            />
          )}
        </div>

        {/* Send / Mic — outside right */}
        <AnimatePresence mode="wait">
          {showSend ? (
            <motion.button
              key="send"
              initial={{ scale: 0.6, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.6, opacity: 0 }}
              transition={{ duration: 0.2 }}
              type="button"
              disabled={blocked_you}
              onClick={sendMessage}
              className="ig-dm-send-btn gentle-transition flex h-11 w-11 shrink-0 items-center justify-center rounded-full text-white shadow-lg active:scale-90"
              aria-label="ارسال"
            >
              <ChatBoldIcon name="send" size={20} className="text-white -mr-0.5" />
            </motion.button>
          ) : (
            <motion.button
              key="mic"
              initial={{ scale: 0.6, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.6, opacity: 0 }}
              transition={{ duration: 0.2 }}
              type="button"
              disabled={blocked_you}
              onPointerDown={handleMicPointerDown}
              onPointerUp={handleMicPointerUp}
              onPointerLeave={() => isRecording && stopRecording(true)}
              className={`gentle-transition flex h-11 w-11 shrink-0 items-center justify-center rounded-full ${
                isRecording
                  ? "scale-110 bg-red-500 text-white shadow-inner"
                  : "ig-dm-send-btn text-white shadow-lg"
              } active:scale-90`}
              aria-label="ضبط ویس"
            >
              {isRecording ? <BoldIcon name="stop" size={20} tinted className="text-white" /> : <ChatBoldIcon name="microphone" size={22} className="text-white" />}
            </motion.button>
          )}
        </AnimatePresence>
      </div>
    </div>
  );
};

export default MessageInput;
