'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { api } from '@/lib/api';
import { useAuthStore } from '@/store/authStore';
import { Button } from '@/components/ui/button';

type SellerStartButtonProps = {
  locale: string;
};

export default function SellerStartButton({ locale }: SellerStartButtonProps) {
  const router = useRouter();
  const token = useAuthStore((state) => state.token);
  const setUser = useAuthStore((state) => state.setUser);
  const [loading, setLoading] = useState(false);

  const handleStart = async () => {
    if (loading) return;
    setLoading(true);

    try {
      if (!token) {
        router.push(`/${locale}/seller-application`);
        return;
      }

      const response = await api.get('/auth/me');
      const user = response.data;
      setUser(user);
      const role = typeof user?.role === 'string' ? user.role : user?.role?.name;
      const sellerArea = ['SELLER', 'ADMIN', 'SUPER_ADMIN'].includes(role);
      router.push(sellerArea ? `/${locale}/seller/dashboard` : `/${locale}/seller-application`);
    } catch {
      router.push(`/${locale}/seller-application`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Button
      type="button"
      onClick={() => void handleStart()}
      disabled={loading}
      className="bg-teal-500 hover:bg-teal-600 text-black font-bold px-8 py-6 rounded-xl shadow-[0_0_20px_rgba(20,184,166,0.3)]"
    >
      {loading ? 'Đang kiểm tra...' : 'Bắt đầu ngay'}
    </Button>
  );
}
