'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuthStore } from '@/lib/store';
import { useTranslation } from '@/lib/i18n';
import SidebarLayout from '@/components/SidebarLayout';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000';

interface VehicleShare {
  id: number;
  user_id: number;
  request_vehicle_id: number;
  share_code: string;
  original_price_krw: number;
  markup_amount_krw: number;
  shared_price_krw: number;
  view_count: number;
  is_purchased: boolean;
  created_at: string;
}

interface ShareReward {
  id: number;
  vehicle_share_id: number;
  markup_amount: number;
  reward_amount: number;
  tax_amount: number;
  net_amount: number;
  status: string;
  created_at: string;
}

interface RewardSummary {
  total_rewards: number;
  total_withdrawn: number;
  pending_amount: number;
  available_for_withdrawal: number;
  reward_count: number;
}

export default function MySharesPage() {
  const { t, language } = useTranslation();
  const { user, token } = useAuthStore();
  const router = useRouter();

  const [tab, setTab] = useState<'shares' | 'rewards'>('shares');
  const [shares, setShares] = useState<VehicleShare[]>([]);
  const [rewards, setRewards] = useState<ShareReward[]>([]);
  const [summary, setSummary] = useState<RewardSummary | null>(null);
  const [loading, setLoading] = useState(true);
  const [copiedId, setCopiedId] = useState<number | null>(null);

  useEffect(() => {
    if (!user) {
      router.push('/login');
      return;
    }

    fetchData();
  }, [user, router]);

  const fetchData = async () => {
    if (!token) return;

    try {
      const [sharesRes, rewardsRes, summaryRes] = await Promise.all([
        fetch(`${API_BASE_URL}/api/share/my-shares`, {
          headers: { 'Authorization': `Bearer ${token}` },
        }),
        fetch(`${API_BASE_URL}/api/share/my-rewards`, {
          headers: { 'Authorization': `Bearer ${token}` },
        }),
        fetch(`${API_BASE_URL}/api/share/my-rewards/summary`, {
          headers: { 'Authorization': `Bearer ${token}` },
        }),
      ]);

      if (sharesRes.ok) setShares(await sharesRes.json());
      if (rewardsRes.ok) setRewards(await rewardsRes.json());
      if (summaryRes.ok) setSummary(await summaryRes.json());
    } catch (error) {
      console.error('Failed to fetch data:', error);
    } finally {
      setLoading(false);
    }
  };

  const copyShareLink = (shareCode: string, shareId: number) => {
    const link = `${window.location.origin}/share/${shareCode}`;
    navigator.clipboard.writeText(link).then(() => {
      setCopiedId(shareId);
      setTimeout(() => setCopiedId(null), 2000);
    });
  };

  const formatPrice = (price: number) => {
    return new Intl.NumberFormat('ko-KR').format(price);
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'pending':
        return <span className="px-2 py-1 bg-yellow-100 text-yellow-700 rounded text-xs">{language === 'ko' ? '대기' : 'Pending'}</span>;
      case 'approved':
        return <span className="px-2 py-1 bg-green-100 text-green-700 rounded text-xs">{language === 'ko' ? '승인' : 'Approved'}</span>;
      case 'withdrawn':
        return <span className="px-2 py-1 bg-blue-100 text-blue-700 rounded text-xs">{language === 'ko' ? '출금완료' : 'Withdrawn'}</span>;
      default:
        return <span className="px-2 py-1 bg-gray-100 text-gray-700 rounded text-xs">{status}</span>;
    }
  };

  if (!user) {
    return null;
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
      </div>
    );
  }

  return (
    <SidebarLayout groupKey="quote">
      <div className="container mx-auto">
        <div className="max-w-4xl mx-auto">
          {/* Header */}
          <div className="mb-6">
            <h1 className="text-2xl font-bold text-gray-800">{t.myShares}</h1>
            <p className="text-gray-600">{t.shareWithFriends}</p>
          </div>

          {/* Summary Card */}
          {summary && (
            <div className="bg-gradient-to-r from-green-600 to-emerald-600 text-white rounded-xl p-6 mb-6">
              <h2 className="text-lg font-semibold mb-4">{t.myRewards}</h2>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div>
                  <p className="text-green-100 text-sm">{language === 'ko' ? '총 리워드' : 'Total Rewards'}</p>
                  <p className="text-2xl font-bold">{formatPrice(summary.total_rewards)}</p>
                </div>
                <div>
                  <p className="text-green-100 text-sm">{language === 'ko' ? '출금 가능' : 'Available'}</p>
                  <p className="text-2xl font-bold">{formatPrice(summary.available_for_withdrawal)}</p>
                </div>
                <div>
                  <p className="text-green-100 text-sm">{language === 'ko' ? '대기 중' : 'Pending'}</p>
                  <p className="text-2xl font-bold">{formatPrice(summary.pending_amount)}</p>
                </div>
                <div>
                  <p className="text-green-100 text-sm">{language === 'ko' ? '출금 완료' : 'Withdrawn'}</p>
                  <p className="text-2xl font-bold">{formatPrice(summary.total_withdrawn)}</p>
                </div>
              </div>
            </div>
          )}

          {/* Info Card */}
          <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
            <div className="flex items-start gap-3">
              <span className="text-2xl">💡</span>
              <p className="text-sm text-blue-700">{t.shareRewardInfo}</p>
            </div>
          </div>

          {/* Tabs */}
          <div className="flex gap-2 mb-6">
            <button
              onClick={() => setTab('shares')}
              className={`px-4 py-2 rounded-lg transition ${
                tab === 'shares'
                  ? 'bg-primary-600 text-white'
                  : 'bg-white text-gray-600 hover:bg-gray-50'
              }`}
            >
              {t.myShares} ({shares.length})
            </button>
            <button
              onClick={() => setTab('rewards')}
              className={`px-4 py-2 rounded-lg transition ${
                tab === 'rewards'
                  ? 'bg-primary-600 text-white'
                  : 'bg-white text-gray-600 hover:bg-gray-50'
              }`}
            >
              {t.myRewards} ({rewards.length})
            </button>
          </div>

          {/* Content */}
          {tab === 'shares' ? (
            <div className="space-y-4">
              {shares.length > 0 ? (
                shares.map((share) => (
                  <div key={share.id} className="bg-white rounded-xl shadow p-4">
                    <div className="flex items-center justify-between mb-3">
                      <div className="flex items-center gap-2">
                        <span className="text-lg">🔗</span>
                        <span className="font-mono text-sm bg-gray-100 px-2 py-1 rounded">
                          {share.share_code}
                        </span>
                      </div>
                      {share.is_purchased ? (
                        <span className="px-3 py-1 bg-green-100 text-green-700 rounded-full text-sm font-medium">
                          {t.purchased}
                        </span>
                      ) : (
                        <span className="px-3 py-1 bg-gray-100 text-gray-600 rounded-full text-sm">
                          {t.notPurchased}
                        </span>
                      )}
                    </div>

                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4 text-sm">
                      <div>
                        <p className="text-gray-500">{t.originalPrice}</p>
                        <p className="font-medium">{formatPrice(share.original_price_krw)}원</p>
                      </div>
                      <div>
                        <p className="text-gray-500">{t.markupAmount}</p>
                        <p className="font-medium text-green-600">+{formatPrice(share.markup_amount_krw)}원</p>
                      </div>
                      <div>
                        <p className="text-gray-500">{t.sharedPrice}</p>
                        <p className="font-medium text-primary-600">{formatPrice(share.shared_price_krw)}원</p>
                      </div>
                      <div>
                        <p className="text-gray-500">{t.viewCount}</p>
                        <p className="font-medium">{share.view_count}</p>
                      </div>
                    </div>

                    <div className="flex items-center justify-between pt-3 border-t">
                      <span className="text-xs text-gray-500">
                        {new Date(share.created_at).toLocaleDateString()}
                      </span>
                      <button
                        onClick={() => copyShareLink(share.share_code, share.id)}
                        className="px-4 py-2 bg-primary-600 text-white text-sm rounded-lg hover:bg-primary-700 transition"
                      >
                        {copiedId === share.id ? t.copied : t.copyShareLink}
                      </button>
                    </div>
                  </div>
                ))
              ) : (
                <div className="bg-white rounded-xl shadow p-8 text-center">
                  <div className="text-4xl mb-4">🔗</div>
                  <p className="text-gray-500">{t.noShares}</p>
                  <p className="text-sm text-gray-400 mt-2">
                    {language === 'ko'
                      ? '내 요청 페이지에서 승인된 차량을 공유할 수 있습니다'
                      : 'You can share approved vehicles from My Requests page'}
                  </p>
                </div>
              )}
            </div>
          ) : (
            <div className="space-y-4">
              {rewards.length > 0 ? (
                rewards.map((reward) => (
                  <div key={reward.id} className="bg-white rounded-xl shadow p-4">
                    <div className="flex items-center justify-between mb-3">
                      <span className="text-lg">💰</span>
                      {getStatusBadge(reward.status)}
                    </div>

                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                      <div>
                        <p className="text-gray-500">{t.markupAmount}</p>
                        <p className="font-medium">{formatPrice(reward.markup_amount)}원</p>
                      </div>
                      <div>
                        <p className="text-gray-500">{t.rewardAmount} (90%)</p>
                        <p className="font-medium text-green-600">{formatPrice(reward.reward_amount)}원</p>
                      </div>
                      <div>
                        <p className="text-gray-500">{t.taxWithheld}</p>
                        <p className="font-medium text-red-600">-{formatPrice(reward.tax_amount)}원</p>
                      </div>
                      <div>
                        <p className="text-gray-500">{t.netAmount}</p>
                        <p className="font-bold text-primary-600">{formatPrice(reward.net_amount)}원</p>
                      </div>
                    </div>

                    <div className="mt-3 pt-3 border-t">
                      <span className="text-xs text-gray-500">
                        {new Date(reward.created_at).toLocaleDateString()}
                      </span>
                    </div>
                  </div>
                ))
              ) : (
                <div className="bg-white rounded-xl shadow p-8 text-center">
                  <div className="text-4xl mb-4">💰</div>
                  <p className="text-gray-500">{t.noRewards}</p>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </SidebarLayout>
  );
}
