'use client';

import { 
  Wallet, FileText, CheckCircle2, AlertCircle, ChevronRight, Check, ShoppingBag, Ticket, Loader2
} from 'lucide-react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { StatisticCard } from '@/components/ui/StatisticCard';
import { useEffect, useState } from 'react';
import { api } from '@/lib/api';
import { useAuthStore } from '@/store/authStore';
import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer
} from 'recharts';

export default function SellerDashboardPage() {
  const pathname = usePathname();
  const currentLocale = pathname.startsWith('/en') ? 'en' : 'vi';
  
  const [stats, setStats] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const user = useAuthStore(s => s.user);

  useEffect(() => {
    const fetchStats = async () => {
      try {
        const res = await api.get('/orders/seller/stats');
        setStats(res.data);
      } catch (e) {
        console.error('Failed to fetch stats', e);
      } finally {
        setLoading(false);
      }
    };
    fetchStats();
  }, []);

  if (loading) {
    return <div className="min-h-screen flex items-center justify-center"><Loader2 className="w-8 h-8 animate-spin text-primary" /></div>;
  }

  // Parse JWT for real user info since authStore might not have it
  let realUser: any = user || {};
  const token = useAuthStore.getState().token;
  if (!user?.email && token) {
    try {
      const base64Url = token.split('.')[1];
      const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
      realUser = JSON.parse(decodeURIComponent(atob(base64).split('').map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)).join('')));
    } catch(e) {}
  }

  const shopName = realUser?.name || realUser?.email?.split('@')[0] || 'My Shop';

  return (
    <div className="space-y-6 pb-20">
      {/* Top Banner Box */}
      <div className="bg-[#1a1313] border border-primary/20 rounded-2xl p-4 flex items-center justify-between">
        <div className="flex items-center gap-4">
          <div className="w-12 h-12 bg-primary rounded-xl flex items-center justify-center shrink-0">
            <span className="text-primary-foreground font-bold">{shopName.substring(0,2).toUpperCase()}</span>
          </div>
          <div>
            <h2 className="text-foreground font-bold text-lg flex items-center gap-2">
              Gian hàng: {shopName}
              <span className="bg-success/10 text-success border border-success/20 text-[10px] px-2 py-0.5 rounded-full uppercase tracking-wider">Đang hoạt động</span>
            </h2>
            <p className="text-muted-foreground text-xs mt-1">{realUser?.email} • Đối tác tin cậy</p>
          </div>
        </div>
        <Link href={`/${currentLocale}/seller/profile`} className="bg-white/5 hover:bg-white/10 text-white text-sm font-medium px-4 py-2 rounded-xl transition-colors shrink-0">
          Xem gian hàng <ChevronRight className="w-4 h-4 inline" />
        </Link>
      </div>

      {/* Stats Row */}
      <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
        <StatisticCard 
          title="Số dư khả dụng" 
          subtitle="Sẵn sàng payout" 
          value={`${(stats?.balance || 0).toLocaleString('vi-VN')} đ`} 
          icon={Wallet} 
          colorClass="primary" 
        />
        <StatisticCard 
          title="Khoản đang giữ" 
          subtitle="Đang chờ release" 
          value={`${(stats?.escrowHold || 0).toLocaleString('vi-VN')} đ`} 
          icon={FileText} 
          colorClass="warning" 
        />
        <StatisticCard 
          title="Tổng đơn (30d)" 
          subtitle="Trong 30 ngày qua" 
          value={stats?.totalOrders?.toString() || '0'} 
          icon={ShoppingBag} 
          colorClass="success" 
        />
        <StatisticCard 
          title="Cần chú ý" 
          subtitle="Đơn hàng chờ xử lý" 
          value={stats?.pendingOrders?.toString() || '0'} 
          icon={AlertCircle} 
          colorClass="orange" 
        />
        <StatisticCard 
          title="Doanh thu (30 ngày)" 
          subtitle="Đơn COMPLETED" 
          value={`${(stats?.revenue30Days || 0).toLocaleString('vi-VN')} đ`} 
          icon={Wallet} 
          colorClass="purple" 
        />
      </div>

      {/* Main Grid: Todo & Health */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Hàng đợi việc cần làm */}
        <div className="bg-card border border-border rounded-2xl p-6 lg:col-span-2 flex flex-col">
          <h3 className="text-foreground font-bold text-lg">Hàng đợi việc cần làm</h3>
          <p className="text-muted-foreground text-sm mb-6">Xử lý các đơn hàng chưa giao để nhận tiền về ví.</p>
          
          <div className="flex-1 flex flex-col items-center justify-center py-10 bg-background rounded-xl border border-border">
            {stats?.pendingOrders > 0 ? (
              <>
                <div className="w-12 h-12 rounded-full bg-orange-500/10 text-orange-500 flex items-center justify-center mb-4">
                  <AlertCircle className="w-6 h-6" />
                </div>
                <p className="text-foreground font-bold">Bạn có {stats.pendingOrders} đơn hàng chờ xử lý!</p>
                <Link href={`/${currentLocale}/seller/orders`} className="mt-4 px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium">Xử lý ngay</Link>
              </>
            ) : (
              <>
                <div className="w-12 h-12 rounded-full bg-success/10 text-success flex items-center justify-center mb-4">
                  <CheckCircle2 className="w-6 h-6" />
                </div>
                <p className="text-foreground font-bold">Không có việc người bán đang chờ</p>
                <p className="text-muted-foreground text-sm">Giữ tồn kho danh mục và theo dõi gian hàng thường xuyên.</p>
              </>
            )}
          </div>
        </div>

        {/* Sức khỏe gian hàng */}
        <div className="bg-card border border-border rounded-2xl p-6">
          <div className="flex justify-between items-end mb-2">
            <h3 className="text-foreground font-bold text-lg">Sức khỏe gian hàng</h3>
            <span className="text-success font-bold text-2xl">96 <span className="text-muted-foreground text-sm">/ 100</span></span>
          </div>
          <p className="text-muted-foreground text-sm mb-4">Hãy kiểm tra thường xuyên để giữ tài khoản an toàn.</p>
          
          <div className="h-2 bg-muted rounded-full mb-6 overflow-hidden">
            <div className="h-full bg-success w-[96%] rounded-full"></div>
          </div>

          <div className="space-y-4">
            <div className="flex justify-between items-center text-sm">
              <span className="text-foreground font-medium">Sản phẩm (Đã đăng)</span>
              <span className="flex items-center gap-2 text-success font-bold">{stats?.products?.total} <CheckCircle2 className="w-4 h-4" /></span>
            </div>
            <div className="flex justify-between items-center text-sm">
              <span className="text-foreground font-medium">Sản phẩm (Đang bán)</span>
              <span className="flex items-center gap-2 text-success font-bold">{stats?.products?.active} <CheckCircle2 className="w-4 h-4" /></span>
            </div>
            <div className="flex justify-between items-center text-sm">
              <span className="text-foreground font-medium">Xử lý đơn hàng</span>
              {stats?.pendingOrders > 0 ? (
                <span className="flex items-center gap-2 text-warning font-bold border border-warning/20 px-2 py-0.5 rounded-md bg-warning/10 text-xs">Chờ giao <ChevronRight className="w-3 h-3" /></span>
              ) : (
                <span className="flex items-center gap-2 text-success font-bold">Tốt <CheckCircle2 className="w-4 h-4" /></span>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Ngữ cảnh tổng quan */}
      <div className="bg-card border border-border rounded-2xl p-6">
        <h3 className="text-foreground font-bold text-lg mb-6">Phân tích kinh doanh (30 ngày)</h3>
        
        <div className="h-[300px] w-full mt-4">
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart data={stats?.trend || []} margin={{ top: 10, right: 10, left: 0, bottom: 0 }}>
              <defs>
                <linearGradient id="colorRevenue" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#8b5cf6" stopOpacity={0.3}/>
                  <stop offset="95%" stopColor="#8b5cf6" stopOpacity={0}/>
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke="#ffffff10" vertical={false} />
              <XAxis 
                dataKey="date" 
                tickFormatter={(val) => {
                  const d = new Date(val);
                  return `${d.getDate()}/${d.getMonth()+1}`;
                }}
                stroke="#ffffff50" 
                fontSize={12} 
                tickLine={false} 
                axisLine={false} 
              />
              <YAxis 
                stroke="#ffffff50" 
                fontSize={12} 
                tickLine={false} 
                axisLine={false}
                tickFormatter={(val) => `${(val / 1000)}k`}
              />
              <Tooltip 
                contentStyle={{ backgroundColor: '#13151a', borderColor: '#ffffff20', borderRadius: '8px' }}
                formatter={(value: any) => {
                  const numericValue = typeof value === 'number' ? value : Number(value ?? 0);
                  return [`${numericValue.toLocaleString('vi-VN')} đ`, 'Doanh thu'];
                }}
                labelFormatter={(label) => `Ngày ${label}`}
              />
              <Area 
                type="monotone" 
                dataKey="revenue" 
                stroke="#8b5cf6" 
                strokeWidth={3}
                fillOpacity={1} 
                fill="url(#colorRevenue)" 
              />
            </AreaChart>
          </ResponsiveContainer>
        </div>
      </div>
    </div>
  );
}
