import React, { useState, useRef, useEffect } from 'react';

// --- Types ---
type Message = {
  id: string;
  sender: 'user' | 'other';
  senderName?: string;
  text: string;
  time: string;
  isReply?: boolean;
  replyTo?: { name: string; text: string };
};

// --- Test Data (From your HTML) ---
const TEST_MESSAGES: Message[] = [
  {
    id: '1',
    sender: 'other',
    senderName: 'Timothy Araujo',
    text: 'Life is sweet if you want it to be.',
    time: '21:39',
  },
  {
    id: '2',
    sender: 'other',
    senderName: 'Timothy Araujo',
    text: 'All this work will pay off, it’s certain.',
    time: '21:39',
  },
  {
    id: '3',
    sender: 'other',
    senderName: 'Simon Atanushe',
    text: 'That’s the way, my guy.',
    time: '21:39',
    isReply: true,
    replyTo: { name: 'Timothy Araujo', text: 'All this work will pay off, it’s certain.' },
  },
  {
    id: '4',
    sender: 'user',
    text: 'Life is sweet if you want it to be.',
    time: '21:39',
  },
  {
    id: '5',
    sender: 'user',
    text: 'All this work will pay off, it’s certain.',
    time: '21:39',
  },
  {
    id: '6',
    sender: 'other',
    senderName: 'Timothy Araujo',
    text: 'God is not wicked. 😭😭',
    time: '21:39',
  },
  {
    id: '7',
    sender: 'other',
    senderName: 'Simon Atanushe',
    text: "Let's cook mfs. I have a gig tonight to build a creative asset for a startup. Need to work on it overnight",
    time: '21:39',
    isReply: true,
    replyTo: { name: 'Timothy Araujo', text: 'All this work will pay off, it’s certain.' },
  },
  {
    id: '8',
    sender: 'other',
    senderName: 'Jeremiah Annuit',
    text: "It's shopify marketing I want to be doing. All this code is not my concern.",
    time: '21:39',
    isReply: true,
    replyTo: { name: 'Timothy Araujo', text: 'All this work will pay off, it’s certain.' },
  },
];

// --- Components ---

const PinnedMessage = () => (
  <div className="flex items-center justify-between gap-4 p-4 border-b border-[#393a3c] bg-[#1a1a1a]/80 backdrop-blur-md sticky top-0 z-10">
    <div className="w-1 h-10 rounded-full bg-[#3f88f7]" />
    <div className="flex-1">
      <h5 className="font-bold text-[#3f88f7] text-sm leading-tight">Pinned Message</h5>
      <p className="text-[#fcfcfc] text-[0.95rem] leading-tight">Me in the next 2 years</p>
    </div>
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
      <path d="M15.3 10.1635L18.748 6.7L18.125 6.077L15.3 8.902L13.875 7.4865L13.252 8.125L15.3 10.1635ZM3.5 19.75V18.25H15V19.75H3.5ZM16.0015 12.75C14.6877 12.75 13.5673 12.287 12.6405 11.361C11.7135 10.435 11.25 9.31517 11.25 8.0015C11.25 6.68767 11.713 5.56733 12.639 4.6405C13.565 3.7135 14.6848 3.25 15.9985 3.25C17.3123 3.25 18.4327 3.713 19.3595 4.639C20.2865 5.565 20.75 6.68483 20.75 7.9985C20.75 9.31233 20.287 10.4327 19.361 11.3595C18.435 12.2865 17.3152 12.75 16.0015 12.75ZM3.5 11.75V10.25H9.3385C9.4295 10.527 9.53233 10.7888 9.647 11.0355C9.76183 11.2823 9.89875 11.5205 10.0578 11.75H3.5ZM3.5 15.75V14.25H12.8328C13.1584 14.4257 13.5027 14.575 13.8655 14.698C14.2283 14.8212 14.6065 14.9097 15 14.9635V15.75H3.5Z" fill="#3f88f7" />
    </svg>
  </div>
);

const MessageBubble = ({ msg }: { msg: Message }) => {
  const isUser = msg.sender === 'user';
  
  return (
    <div className={`flex w-full gap-3 mb-4 ${isUser ? 'justify-end' : 'justify-start'}`}>
      {!isUser && (
        <div className="w-[44px] h-[44px] rounded-full shrink-0 bg-blue-400 border border-gray-700 self-end" />
      )}
      
      <div className={`relative max-w-[70%] p-3 rounded-[20px] backdrop-blur-md 
        ${isUser 
          ? 'bg-gradient-to-r from-[#924BEF] via-[#9147F6] to-[#9649FB] rounded-br-none' 
          : 'bg-gradient-to-l from-[#2A2134] via-[#2B2235] to-[#2B2235] rounded-bl-none'
        }`}
      >
        {/* Reply Context */}
        {msg.isReply && msg.replyTo && (
          <div className="mb-2 pl-2 border-l-[3px] border-[#3598b5] bg-[#2d3041] rounded py-1">
            <p className="text-xs text-[#3598b5] font-bold">{msg.replyTo.name}</p>
            <p className="text-xs text-white opacity-80 truncate">{msg.replyTo.text}</p>
          </div>
        )}

        {/* Sender Name (Only for others) */}
        {!isUser && msg.senderName && (
          <span className="block text-[#5a72af] text-[0.85rem] font-bold mb-1">
            {msg.senderName}
          </span>
        )}

        {/* Message Text */}
        <p className="text-[#fcfcfc] font-medium leading-normal mb-1">
          {msg.text}
        </p>

        {/* Timestamp */}
        <div className="flex justify-end items-end w-full">
          <span className={`text-[0.7rem] ${isUser ? 'text-white/60' : 'text-gray-400'}`}>
            {msg.time}
          </span>
        </div>

        {/* SVG Tails (Exact Geometry from CSS) */}
        {!isUser && (
          <div 
            className="absolute -left-[6px] bottom-[0px] w-[30px] h-[30px] bg-gradient-to-l from-[#2A2134] to-[#2B2235] z-[-1]" 
            style={{ clipPath: 'path("M5.5 6.5C6.3 3.7 6.16667 1.33333 6 0.5H14.5C14.5 3 14.5 7 11.5 10C9.85076 11.6492 4.66667 12.5 2 12.5C2.83333 11.6667 4.7 9.3 5.5 6.5Z")' }}
          />
        )}
        {isUser && (
          <div 
            className="absolute -right-[6px] bottom-[0px] w-[30px] h-[30px] bg-gradient-to-r from-[#9649FB] to-[#924BEF] z-[-1]"
            style={{ clipPath: 'path("M10 7C9.2 4.2 9.33333 1.83333 9.5 1H1C1 3.5 1 7.5 4 10.5C5.64924 12.1492 10.8333 13 13.5 13C12.6667 12.1667 10.8 9.8 10 7Z")' }}
          />
        )}
      </div>
    </div>
  );
};

const ScrollDownCircle = ({ onClick }: { onClick: () => void }) => (
  <button 
    onClick={onClick}
    className="absolute bottom-6 right-6 w-9 h-9 bg-[#1b1c21] border border-[#232426] rounded-full grid place-content-center shadow-lg hover:bg-[#25262b] transition-colors z-20"
  >
    <svg width="20" height="20" viewBox="0 0 33 33" fill="none">
       <path d="M16.5633 20.4233L9.025 12.8846L10.43 11.4796L16.5633 17.5926L22.6967 11.4796L24.1017 12.8846L16.5633 20.4233Z" fill="#5a72af" />
    </svg>
  </button>
);

// --- Main Container ---

interface TestChatLayoutProps {
  testMode?: boolean; // Toggle testing on/off
}

const TestChatLayout = ({ testMode = true }: TestChatLayoutProps) => {
  const [messages, setMessages] = useState<Message[]>(testMode ? TEST_MESSAGES : []);
  const bottomRef = useRef<HTMLDivElement>(null);

  const scrollToBottom = () => {
    bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    if (testMode) {
      setMessages(TEST_MESSAGES);
    } else {
      setMessages([]);
    }
  }, [testMode]);

  return (
    <div className="relative w-full h-screen bg-[#000000] text-[#8b8b8b] font-sans overflow-hidden flex flex-col">
      
      {/* 1. Pinned Message */}
      <PinnedMessage />

      {/* 2. Messages List */}
      <div className="flex-1 overflow-y-auto p-4 pb-24 scroll-smooth">
        {messages.map((msg) => (
          <MessageBubble key={msg.id} msg={msg} />
        ))}
        
        {/* Empty State Helper */}
        {!testMode && messages.length === 0 && (
          <div className="h-full flex items-center justify-center text-gray-600">
            No messages (Test Mode Off)
          </div>
        )}
        
        <div ref={bottomRef} />
      </div>

      {/* 3. Scroll Down Circle */}
      <ScrollDownCircle onClick={scrollToBottom} />

    </div>
  );
};

export default TestChatLayout;