'use client';
import { useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import InterviewInterface from '@/components/InterviewInterface';
import { clients, auth, type Client, type User } from '@/utils/api';
import toast from 'react-hot-toast';

export default function InterviewPage() {
  const { clientId } = useParams<{ clientId: string }>();
  const router = useRouter();
  const [client, setClient] = useState<Client | null>(null);
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const init = async () => {
      try {
        const token = localStorage.getItem('muse_token');
        if (token) {
          const { user: u } = await auth.verify();
          setUser(u);
        }
        const { client: c } = await clients.get(clientId);
        setClient(c);
      } catch (err: any) {
        toast.error(err.message || 'Failed to load interview');
        router.push('/');
      } finally {
        setLoading(false);
      }
    };
    init();
  }, [clientId, router]);

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center" style={{ background: 'var(--bg-primary)' }}>
        <div className="flex gap-1.5">
          <div className="typing-dot" />
          <div className="typing-dot" style={{ animationDelay: '0.2s' }} />
          <div className="typing-dot" style={{ animationDelay: '0.4s' }} />
        </div>
      </div>
    );
  }

  if (!client) return null;

  return (
    <InterviewInterface
      client={client}
      user={user}
      onBack={() => window.location.href = '/'}
      onClientUpdate={setClient}
    />
  );
}
