'use client';

import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { useMutation, useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { useAuthStore } from '@/store/authStore';
import { Button } from '@/components/ui/button';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Input } from '@/components/ui/input';

const sellerApplicationSchema = z.object({
  shopName: z.string().min(3, 'Tên gian hàng là bắt buộc').max(100),
  businessType: z.string().min(3, 'Loại hình kinh doanh là bắt buộc').max(100),
  website: z.string().url('URL không hợp lệ').optional().or(z.literal('')),
  description: z.string().min(10, 'Mô tả càng cụ thể càng tốt').max(500),
  reason: z.string().min(10, 'Hãy cho biết lý do bạn muốn bán hàng trên SHOPMMO').max(500),
  experience: z.string().max(500).optional().or(z.literal('')),
});

type SellerApplicationForm = z.infer<typeof sellerApplicationSchema>;

export default function SellerApplicationPage() {
  const pathname = usePathname();
  const locale = pathname.startsWith('/en') ? 'en' : 'vi';
  const router = useRouter();
  const token = useAuthStore((s) => s.token);
  const [ready, setReady] = useState(false);

  useEffect(() => {
    setReady(true);
  }, []);

  const form = useForm<SellerApplicationForm>({
    resolver: zodResolver(sellerApplicationSchema),
    defaultValues: {
      shopName: '',
      businessType: '',
      website: '',
      description: '',
      reason: '',
      experience: '',
    },
  });

  const applicationQuery = useQuery({
    queryKey: ['sellerApplication'],
    queryFn: async () => {
      const response = await api.get('/seller/application');
      return response.data;
    },
    enabled: !!token,
    retry: false,
    staleTime: 1000 * 60 * 5,
  });

  const applicationMutation = useMutation({
    mutationFn: async (values: SellerApplicationForm) => {
      const response = await api.post('/seller/application', values);
      return response.data;
    },
    onSuccess: () => {
      router.push(`/${locale}/seller/dashboard`);
    },
  });

  if (!ready) {
    return null;
  }

  const hasApplication = !!applicationQuery.data;
  const applicationStatus = applicationQuery.data?.status;

  return (
    <div className="min-h-screen bg-[#0f1117] py-10 px-4">
      <div className="mx-auto max-w-4xl">
        <div className="mb-8 text-center">
          <h1 className="text-4xl font-black text-white">Đăng ký Seller</h1>
          <p className="mt-3 text-gray-400 max-w-2xl mx-auto">
            Đăng ký để tạo gian hàng và bán sản phẩm số trên SHOPMMO. Nếu bạn chưa có tài khoản mua hàng, hãy đăng ký tài khoản trước rồi đăng nhập.
          </p>
        </div>

        {!token ? (
          <div className="rounded-3xl border border-white/10 bg-white/5 p-8 text-center">
            <p className="text-lg text-white font-semibold">Bạn cần đăng nhập hoặc đăng ký tài khoản mua hàng trước.</p>
            <div className="mt-6 flex flex-col gap-3 sm:flex-row sm:justify-center">
              <Link href={`/${locale}/auth/login`} className="w-full sm:w-auto">
                <Button className="w-full bg-primary text-white">Đăng nhập</Button>
              </Link>
              <Link href={`/${locale}/auth/register`} className="w-full sm:w-auto">
                <Button variant="outline" className="w-full border-white/20 text-white">Đăng ký tài khoản</Button>
              </Link>
            </div>
          </div>
        ) : applicationQuery.isLoading ? (
          <div className="rounded-3xl border border-white/10 bg-white/5 p-8 text-center text-white">Đang kiểm tra trạng thái đơn đăng ký...</div>
        ) : applicationQuery.isError ? (
          <div className="rounded-3xl border border-white/10 bg-red-500/10 p-8 text-center text-red-200">Không thể tải thông tin. Vui lòng thử lại sau.</div>
        ) : hasApplication ? (
          <div className="rounded-3xl border border-white/10 bg-white/5 p-8">
            <h2 className="text-2xl font-semibold text-white">Trạng thái đơn đăng ký</h2>
            <p className="mt-3 text-gray-300">Đơn đăng ký hiện tại của bạn đang ở trạng thái:</p>
            <div className="mt-4 rounded-2xl bg-[#111317] p-5 text-white">
              <p className="font-semibold">{applicationStatus || 'PENDING'}</p>
              <p className="mt-2 text-gray-400">Shop: {applicationQuery.data?.shopName || '---'}</p>
              {applicationQuery.data?.reason && <p className="mt-2 text-gray-400">Lý do: {applicationQuery.data.reason}</p>}
              {applicationQuery.data?.experience && <p className="mt-2 text-gray-400">Kinh nghiệm: {applicationQuery.data.experience}</p>}
            </div>
            <div className="mt-6 flex flex-col sm:flex-row gap-3">
              <Link href={`/${locale}/seller/dashboard`} className="w-full sm:w-auto">
                <Button className="w-full">Về Seller Dashboard</Button>
              </Link>
              <Link href={`/${locale}`} className="w-full sm:w-auto">
                <Button variant="outline" className="w-full text-white border-white/20">Về trang chủ</Button>
              </Link>
            </div>
          </div>
        ) : (
          <div className="rounded-3xl border border-white/10 bg-white/5 p-8">
            <h2 className="text-2xl font-semibold text-white mb-3">Thông tin đăng ký seller</h2>
            {applicationMutation.isError && (
              <div className="rounded-xl border border-red-500/20 bg-red-500/10 p-4 mb-4 text-sm text-red-200">
                {(applicationMutation.error as any)?.response?.data?.message || 'Không thể gửi đơn đăng ký'}
              </div>
            )}
            <Form {...form}>
              <form onSubmit={form.handleSubmit((values) => applicationMutation.mutate(values))} className="space-y-4">
                <FormField control={form.control} name="shopName" render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-gray-300">Tên gian hàng</FormLabel>
                    <FormControl>
                      <Input placeholder="Ví dụ: SHOPMMO Digital Store" {...field} className="bg-white/5 border-white/10 text-white" />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )} />

                <FormField control={form.control} name="businessType" render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-gray-300">Loại hình kinh doanh</FormLabel>
                    <FormControl>
                      <Input placeholder="Ví dụ: Bán key phần mềm, thẻ game, dịch vụ số" {...field} className="bg-white/5 border-white/10 text-white" />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )} />

                <FormField control={form.control} name="website" render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-gray-300">Website / Fanpage (nếu có)</FormLabel>
                    <FormControl>
                      <Input placeholder="https://" {...field} className="bg-white/5 border-white/10 text-white" />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )} />

                <FormField control={form.control} name="description" render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-gray-300">Mô tả gian hàng</FormLabel>
                    <FormControl>
                      <Input placeholder="Mô tả ngắn gọn về sản phẩm và dịch vụ bạn muốn bán" {...field} className="bg-white/5 border-white/10 text-white" />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )} />

                <FormField control={form.control} name="reason" render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-gray-300">Lý do bạn muốn bán hàng tại SHOPMMO</FormLabel>
                    <FormControl>
                      <Input placeholder="Vì sao bạn chọn SHOPMMO để kinh doanh" {...field} className="bg-white/5 border-white/10 text-white" />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )} />

                <FormField control={form.control} name="experience" render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-gray-300">Kinh nghiệm bán hàng (nếu có)</FormLabel>
                    <FormControl>
                      <Input placeholder="Ví dụ: 2 năm kinh nghiệm bán key game" {...field} className="bg-white/5 border-white/10 text-white" />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )} />

                <Button type="submit" className="w-full h-12 bg-primary text-white">
                  {applicationMutation.status === 'pending' ? 'Đang gửi...' : 'Gửi đăng ký bán hàng'}
                </Button>
              </form>
            </Form>
          </div>
        )}
      </div>
    </div>
  );
}
