import { useState, useEffect, useRef } from 'react';
import { useClubsStore } from '../store/clubs';
import { useAuthStore } from '../store/auth';
import { Send, Image, Loader2, X, RefreshCw, MessageSquare } from 'lucide-react';
import ProgressBar from './ui/ProgressBar';

interface ChatProps {
  clubId: number;
  clubName: string;
}

export default function ExtracurricularChat({ clubId, clubName }: ChatProps) {
  const { user } = useAuthStore();
  const { chats, fetchChats, sendChatMessage, uploadChatImage, uploadProgress } = useClubsStore();
  
  const [messageText, setMessageText] = useState('');
  const [selectedImage, setSelectedImage] = useState<File | null>(null);
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const [uploadingImage, setUploadingImage] = useState(false);
  const [sending, setSending] = useState(false);
  const [refreshing, setRefreshing] = useState(false);

  const fileInputRef = useRef<HTMLInputElement>(null);
  const chatEndRef = useRef<HTMLDivElement>(null);

  // Initial fetch and poll
  useEffect(() => {
    fetchChats(clubId);

    const interval = setInterval(() => {
      fetchChats(clubId);
    }, 5000); // poll every 5s

    return () => clearInterval(interval);
  }, [clubId]);

  // Scroll to bottom on new messages
  useEffect(() => {
    chatEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [chats]);

  useEffect(() => {
    if (!window.visualViewport) return;
    const handleViewportChange = () => {
      chatEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    };
    window.visualViewport.addEventListener('resize', handleViewportChange);
    window.visualViewport.addEventListener('scroll', handleViewportChange);
    return () => {
      window.visualViewport?.removeEventListener('resize', handleViewportChange);
      window.visualViewport?.removeEventListener('scroll', handleViewportChange);
    };
  }, []);

  const handleRefresh = async () => {
    setRefreshing(true);
    try {
      await fetchChats(clubId);
    } catch (err) {
      console.error(err);
    } finally {
      setRefreshing(false);
    }
  };

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      const file = e.target.files[0];
      setSelectedImage(file);
      setImagePreview(URL.createObjectURL(file));
    }
  };

  const handleClearImage = () => {
    setSelectedImage(null);
    setImagePreview(null);
    if (fileInputRef.current) fileInputRef.current.value = '';
  };

  const handleSend = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!messageText.trim() && !selectedImage) return;

    setSending(true);
    try {
      let uploadedUrl = '';
      if (selectedImage) {
        setUploadingImage(true);
        uploadedUrl = await uploadChatImage(selectedImage);
        setUploadingImage(false);
      }

      await sendChatMessage(clubId, messageText, uploadedUrl || undefined);
      setMessageText('');
      handleClearImage();
    } catch (err) {
      alert('Failed to send message');
    } finally {
      setSending(false);
      setUploadingImage(false);
    }
  };

  const getRoleBadgeColor = (role?: string) => {
    switch (role) {
      case 'systems_admin':
      case 'school_admin':
        return 'bg-red-50 text-red-600 border-red-100 dark:bg-red-950/20 dark:text-red-400 dark:border-red-900/30';
      case 'teacher':
      case 'clubs_head':
        return 'bg-purple-50 text-purple-600 border-purple-100 dark:bg-purple-950/20 dark:text-purple-400 dark:border-purple-900/30';
      default:
        return 'bg-blue-50 text-blue-600 border-blue-100 dark:bg-blue-950/20 dark:text-blue-400 dark:border-blue-900/30';
    }
  };

  const formatTime = (dateStr: string) => {
    try {
      const date = new Date(dateStr);
      return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    } catch (e) {
      return '';
    }
  };

  return (
    <div className="bg-card border border-border rounded-2xl sm:rounded-[2.5rem] shadow-sm flex flex-col h-[calc(100dvh-180px)] sm:h-[600px] max-h-[85dvh] overflow-hidden">
      {/* Chat Header */}
      <div className="px-5 sm:px-8 py-4 sm:py-5 border-b border-border bg-muted/20 flex justify-between items-center shrink-0">
        <div className="flex items-center gap-3">
          <div className="w-9 h-9 sm:w-10 sm:h-10 rounded-xl bg-primary/10 text-primary flex items-center justify-center shrink-0">
            <MessageSquare size={18} />
          </div>
          <div>
            <h4 className="font-black text-text text-xs sm:text-sm uppercase tracking-tight truncate">{clubName} Chat Room</h4>
            <p className="text-[0.6rem] sm:text-[0.65rem] text-text-muted font-bold uppercase tracking-widest mt-0.5">Active Conversation</p>
          </div>
        </div>
        <button 
          onClick={handleRefresh}
          disabled={refreshing}
          className="p-2 text-text-muted hover:text-primary rounded-lg hover:bg-muted/50 transition-colors disabled:opacity-50 cursor-pointer"
          title="Refresh Messages"
        >
          <RefreshCw size={16} className={refreshing ? 'animate-spin' : ''} />
        </button>
      </div>

      {/* Messages list */}
      <div className="flex-1 overflow-y-auto p-4 sm:p-6 md:p-8 space-y-4 sm:space-y-6 custom-scrollbar">
        {chats.length === 0 ? (
          <div className="h-full flex flex-col items-center justify-center text-center text-text-muted space-y-4">
            <MessageSquare size={48} className="text-text-muted/30" />
            <div>
              <p className="font-bold text-sm uppercase tracking-widest">No messages yet</p>
              <p className="text-xs font-medium max-w-xs mx-auto mt-1">Start the conversation by sending the first message to the team!</p>
            </div>
          </div>
        ) : (
          chats.map((chat) => {
            const isOwnMessage = chat.sender_id === user?.id;
            return (
              <div 
                key={chat.id} 
                className={`flex gap-3 max-w-[85%] sm:max-w-[80%] ${isOwnMessage ? 'ml-auto flex-row-reverse' : ''}`}
              >
                {/* Avatar */}
                <div className="w-8 h-8 sm:w-9 sm:h-9 rounded-xl bg-primary/10 border border-border flex items-center justify-center text-xs font-bold text-primary shrink-0 uppercase shadow-sm">
                  {chat.sender_name ? chat.sender_name.charAt(0) : '?'}
                </div>

                {/* Message Body */}
                <div className="space-y-1">
                  {/* Sender Name and Role */}
                  <div className={`flex items-center gap-2 text-[0.65rem] font-bold text-text-muted ${isOwnMessage ? 'justify-end' : ''}`}>
                    <span>{chat.sender_name}</span>
                    <span className={`px-1.5 py-0.5 rounded border text-[0.55rem] uppercase font-black tracking-widest scale-90 ${getRoleBadgeColor(chat.sender_role)}`}>
                      {chat.sender_role === 'student' ? 'Student' : chat.sender_role === 'teacher' ? 'Teacher' : 'Staff'}
                    </span>
                  </div>

                  {/* Bubble */}
                  <div className={`p-3.5 sm:p-4 rounded-2xl sm:rounded-3xl border shadow-sm ${
                    isOwnMessage 
                      ? 'bg-primary text-white border-primary rounded-tr-none' 
                      : 'bg-card text-text border-border rounded-tl-none'
                  }`}>
                    {chat.message && (
                      <p className="text-xs sm:text-sm font-medium leading-relaxed whitespace-pre-wrap">{chat.message}</p>
                    )}

                    {chat.image_url && (
                      <div className={`overflow-hidden rounded-2xl ${chat.message ? 'mt-3' : ''}`}>
                        <img
                          src={`${chat.image_url}`}
                          alt="Uploaded attachment"
                          className="max-w-full max-h-60 object-cover hover:scale-105 transition-transform cursor-pointer"
                          onClick={() => window.open(`${chat.image_url}`, '_blank')}
                        />
                      </div>
                    )}
                  </div>

                  {/* Time */}
                  <div className={`text-[0.6rem] font-bold text-text-muted/60 ${isOwnMessage ? 'text-right' : ''}`}>
                    {formatTime(chat.created_at)}
                  </div>
                </div>
              </div>
            );
          })
        )}
        <div ref={chatEndRef} />
      </div>

      {/* Input area */}
      <form onSubmit={handleSend} className="p-3 sm:p-4 border-t border-border bg-muted/20 shrink-0 space-y-3 sticky bottom-0 z-10 pb-[env(safe-area-inset-bottom,0px)]">
        {imagePreview && (
          <div className="flex items-center gap-3 p-2 bg-card border border-border rounded-2xl animate-in slide-in-from-bottom duration-200">
            <div className="relative w-14 h-14 sm:w-16 sm:h-16 rounded-xl overflow-hidden border border-border">
              <img src={imagePreview} alt="Upload preview" className="w-full h-full object-cover" />
              {uploadingImage && (
                <div className="absolute inset-0 bg-black/60 flex flex-col items-center justify-center gap-1.5 px-1.5">
                  <Loader2 className="animate-spin text-white" size={16} />
                  <ProgressBar
                    value={uploadProgress}
                    size="xs"
                    className="w-full"
                    aria-label="Image upload progress"
                  />
                </div>
              )}
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-xs font-bold text-text truncate">{selectedImage?.name}</p>
              <p className="text-[0.6rem] text-text-muted uppercase font-black tracking-widest mt-0.5">Ready to attach</p>
            </div>
            <button 
              type="button" 
              onClick={handleClearImage}
              className="p-1.5 text-text-muted hover:text-rose-500 rounded-lg hover:bg-muted/50 transition-colors cursor-pointer"
            >
              <X size={16} />
            </button>
          </div>
        )}

        <div className="flex items-center gap-2 sm:gap-3">
          <input 
            type="file" 
            ref={fileInputRef} 
            onChange={handleImageChange} 
            accept="image/*" 
            className="hidden" 
          />
          <button
            type="button"
            onClick={() => fileInputRef.current?.click()}
            className="p-2.5 sm:p-3 text-text-muted hover:text-primary hover:bg-muted/50 rounded-2xl border border-border bg-card transition-all shrink-0 cursor-pointer"
            title="Attach Image"
          >
            <Image size={18} />
          </button>
          
          <input
            type="text"
            className="flex-1 bg-card border border-border rounded-2xl px-4 sm:px-5 py-3 sm:py-3.5 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-primary/5 focus:border-primary text-text shadow-sm"
            placeholder="Write a message to your team..."
            value={messageText}
            onChange={e => setMessageText(e.target.value)}
            onFocus={() => {
              setTimeout(() => chatEndRef.current?.scrollIntoView({ behavior: 'smooth' }), 100);
              setTimeout(() => chatEndRef.current?.scrollIntoView({ behavior: 'smooth' }), 300);
            }}
            disabled={sending}
          />
          
          <button
            type="submit"
            disabled={(sending || (!messageText.trim() && !selectedImage))}
            className="p-3 sm:p-3.5 bg-primary text-white rounded-2xl hover:bg-primary/95 transition-all shadow-md active:scale-95 disabled:opacity-50 disabled:scale-100 flex items-center justify-center shrink-0 cursor-pointer"
          >
            {sending ? <Loader2 size={16} className="animate-spin" /> : <Send size={16} />}
          </button>
        </div>
      </form>
    </div>
  );
}
