'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import { useAuth } from '@/app/hooks/useAuth';
import { useChat } from '@/app/hooks/useChat';
import { useOllamaStatus } from '@/app/hooks/useOllamaStatus';
import { AccountBox } from '@/app/components/AccountBox';
import { ChatInput } from '@/app/components/ChatInput';
import { ChatMessage } from '@/app/components/ChatMessage';
import { Sidebar } from '@/app/components/Sidebar';
import { WelcomeScreen } from '@/app/components/WelcomeScreen';
import { useT } from '@/app/components/ContentProvider';
import { CustomerProvider } from '@/app/components/CustomerProvider';
import { ChevronRightIcon } from '@/app/components/icons';
import { branding } from '@/app/config/branding';

export default function Home() {
  const {
    conversations, activeConvId, messages, loading, streamingId, opening, notice, customer, dismissNotice, reload,
    sendMessage, startNewConversation, loadConversation, deleteConversation, clearAllHistory,
  } = useChat();
  // After signing in or out the list is read again: it is now a different person's conversations.
  const auth = useAuth({ onChange: reload });
  const status = useOllamaStatus();
  const t = useT();

  const [input, setInput] = useState('');
  const bottomRef = useRef<HTMLDivElement>(null);
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages, loading]);

  const handleSubmit = useCallback(() => {
    const text = input.trim();
    if (!text || loading) return;
    setInput('');
    void sendMessage(text);
  }, [input, loading, sendMessage]);

  const pickSuggestion = useCallback((prompt: string) => {
    setInput(prompt);
    textareaRef.current?.focus();
  }, []);

  const handleNew = useCallback(() => {
    startNewConversation();
    setInput('');
  }, [startNewConversation]);

  const activeTitle = conversations.find(c => c.id === activeConvId)?.title
    ?? (activeConvId ? t('copy.untitledConversation') : t('copy.newConversation'));

  return (
    <div className="flex h-screen overflow-hidden bg-page font-sans text-ink">
      <Sidebar
        conversations={conversations}
        activeConvId={activeConvId}
        status={status}
        account={auth.available ? <AccountBox user={auth.user} onSubmit={auth.signIn} onSignOut={auth.signOut} /> : undefined}
        onNew={handleNew}
        onSelect={loadConversation}
        onDelete={deleteConversation}
        onClearAll={clearAllHistory}
        onPickSuggestion={pickSuggestion}
      />

      <main className="flex min-w-0 flex-1 flex-col">
        <header className="flex h-12 shrink-0 items-center justify-between border-b border-line bg-header px-5 backdrop-blur-[20px]">
          <div className="flex min-w-0 items-center gap-1.5">
            <span className="text-[14px] text-muted">{branding.appName}</span>
            <ChevronRightIcon color="var(--color-faint)" />
            <span className="max-w-[340px] overflow-hidden text-[16px] font-semibold text-ellipsis whitespace-nowrap text-ink">
              {activeTitle}
            </span>
          </div>
          <div className="flex shrink-0 items-center gap-2">
            <span
              title={customer ? `${t('header.customer')}: ${customer.name} (#${customer.id})` : undefined}
              className="max-w-[260px] overflow-hidden rounded-md border border-line bg-tint px-2 py-[3px] text-[12px] text-ellipsis whitespace-nowrap text-ink-2"
            >
              {customer ? <><span className="text-muted">{t('header.customer')}:</span> <span className="font-semibold">{customer.name}</span></> : <span className="text-muted">{t('header.noCustomer')}</span>}
            </span>
            <div className="flex items-center gap-[5px] rounded-md border border-line bg-panel px-2 py-[3px]">
              <span className={`block size-1.5 rounded-[50%] ${loading ? 'bg-accent' : 'bg-success'}`} />
              <span className="text-[12px] text-muted">{loading ? t('header.streaming') : t('header.ready')}</span>
            </div>
          </div>
        </header>

        {notice && (
          <div role="status" className="flex shrink-0 items-center justify-between gap-3 border-b border-warning/30 bg-warning/10 px-5 py-1.5 text-[13px] text-warning-ink">
            <span>{notice}</span>
            <button onClick={dismissNotice} className="cursor-pointer border-0 bg-transparent p-0 text-[13px] font-semibold text-warning-ink hover:underline">{t('notice.dismiss')}</button>
          </div>
        )}

        <div className="flex-1 overflow-y-auto bg-page">
          {messages.length === 0 ? (
            opening ? null : <WelcomeScreen onPickSuggestion={pickSuggestion} />
          ) : (
            <CustomerProvider customer={customer}>
              <div className="mx-auto flex w-full max-w-chat flex-col gap-5 px-4 py-6">
                {messages.map(msg => (
                  <ChatMessage key={msg.id} msg={msg} isStreaming={streamingId === msg.id && loading} />
                ))}
                <div ref={bottomRef} />
              </div>
            </CustomerProvider>
          )}
        </div>

        <ChatInput value={input} loading={loading} textareaRef={textareaRef} onChange={setInput} onSubmit={handleSubmit} />
      </main>
    </div>
  );
}
