"use client";

import { useState, useRef, useEffect, useCallback } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { FiMic, FiPaperclip, FiSend, FiSquare } from "react-icons/fi";
import AttachmentMenu, { AttachmentType } from "./AttachmentMenu";

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;
}

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,
}: 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 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 px-3 sm:px-4 ${
        isChatThread ? "bottom-0 chat-input-area--thread" : "bottom-[5.5rem] chat-input-area"
      }`}
    >
      {replyLabel && (
        <div className="pointer-events-auto mb-2 flex w-full max-w-lg items-center gap-2 rounded-2xl border-r-2 border-[#0095f6] bg-white/80 px-3 py-2 text-xs backdrop-blur-md dark:bg-neutral-900/80">
          <span className="flex-1 truncate text-neutral-600 dark:text-neutral-300">
            {replyLabel}
          </span>
          <button
            type="button"
            onClick={onCancelReply}
            className="shrink-0 text-[#0095f6]"
          >
            ×
          </button>
        </div>
      )}
      <div
        dir="ltr"
        className="pointer-events-auto relative flex w-full max-w-lg items-end gap-2 sm:gap-3"
      >
        <div className="relative mb-1">
          <button
            ref={attachBtnRef}
            type="button"
            disabled={blocked_you || isRecording}
            onClick={() => setMenuOpen((o) => !o)}
            className="chat-action-btn gentle-transition flex h-10 w-10 shrink-0 items-center justify-center rounded-full active:scale-90 disabled:opacity-40 sm:h-11 sm:w-11"
            aria-label="پیوست"
          >
            <FiPaperclip size={22} className="rotate-[-45deg]" />
          </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-[44px] 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"
              >
                <FiSquare size={18} />
              </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 mb-1 flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-white shadow-lg active:scale-90 sm:h-11 sm:w-11"
              aria-label="ارسال"
            >
              <FiSend size={20} className="-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 mb-1 flex h-10 w-10 shrink-0 items-center justify-center rounded-full sm:h-11 sm:w-11 ${
                isRecording
                  ? "scale-110 bg-red-500 text-white shadow-inner"
                  : "ig-dm-send-btn text-white shadow-lg"
              } active:scale-90`}
              aria-label="ضبط ویس"
            >
              {isRecording ? <FiSquare size={20} /> : <FiMic size={22} />}
            </motion.button>
          )}
        </AnimatePresence>
      </div>
    </div>
  );
};

export default MessageInput;
