'use client';

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

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

  const [inquiries, setInquiries] = useState<Inquiry[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);

  useEffect(() => {
    if (!user) {
      router.push('/login?redirect=/my-inquiries');
      return;
    }

    fetchInquiries();
  }, [user, router, page]);

  const fetchInquiries = async () => {
    try {
      setLoading(true);
      const response = await inquiryApi.getMyInquiries(page, 10);
      setInquiries(response.inquiries || []);
      setTotalPages(response.total_pages || 1);
    } catch (error) {
      console.error('Failed to fetch inquiries:', error);
    } finally {
      setLoading(false);
    }
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'pending':
        return (
          <span className="px-2 py-1 bg-yellow-100 text-yellow-700 rounded-full text-xs">
            {language === 'ko' ? '대기중' : 'Pending'}
          </span>
        );
      case 'in_progress':
        return (
          <span className="px-2 py-1 bg-blue-100 text-blue-700 rounded-full text-xs">
            {language === 'ko' ? '처리중' : 'In Progress'}
          </span>
        );
      case 'resolved':
        return (
          <span className="px-2 py-1 bg-green-100 text-green-700 rounded-full text-xs">
            {language === 'ko' ? '해결됨' : 'Resolved'}
          </span>
        );
      case 'closed':
        return (
          <span className="px-2 py-1 bg-gray-100 text-gray-700 rounded-full text-xs">
            {language === 'ko' ? '종료' : 'Closed'}
          </span>
        );
      default:
        return (
          <span className="px-2 py-1 bg-gray-100 text-gray-700 rounded-full text-xs">
            {status}
          </span>
        );
    }
  };

  const getCategoryLabel = (category: string) => {
    const categories: Record<string, { ko: string; en: string }> = {
      general: { ko: '일반', en: 'General' },
      vehicle: { ko: '차량', en: 'Vehicle' },
      payment: { ko: '결제', en: 'Payment' },
      shipping: { ko: '배송', en: 'Shipping' },
      account: { ko: '계정', en: 'Account' },
      other: { ko: '기타', en: 'Other' },
    };
    return categories[category]?.[language === 'ko' ? 'ko' : 'en'] || category;
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString(language === 'ko' ? 'ko-KR' : 'en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    });
  };

  if (!user) {
    return null;
  }

  return (
    <SidebarLayout groupKey="inquiry">
      <div className="container mx-auto">
        <div className="max-w-3xl mx-auto">
          {/* Header */}
          <div className="flex justify-between items-center mb-6">
            <div>
              <h1 className="text-2xl font-bold text-gray-800">
                {language === 'ko' ? '내 문의 목록' : 'My Inquiries'}
              </h1>
              <p className="text-gray-600">
                {language === 'ko' ? '문의 내역을 확인하세요' : 'Check your inquiry history'}
              </p>
            </div>
            <Link
              href="/inquiry"
              className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition font-medium"
            >
              {language === 'ko' ? '새 문의' : 'New Inquiry'}
            </Link>
          </div>

          {/* Loading */}
          {loading && (
            <div className="flex justify-center py-12">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
            </div>
          )}

          {/* Empty State */}
          {!loading && inquiries.length === 0 && (
            <div className="bg-white rounded-xl shadow p-12 text-center">
              <div className="text-5xl mb-4">📭</div>
              <h3 className="text-xl font-semibold text-gray-700 mb-2">
                {language === 'ko' ? '문의 내역이 없습니다' : 'No inquiries yet'}
              </h3>
              <p className="text-gray-500 mb-6">
                {language === 'ko'
                  ? '궁금한 점이 있으시면 문의해주세요'
                  : 'If you have any questions, please submit an inquiry'}
              </p>
              <Link
                href="/inquiry"
                className="inline-block px-6 py-3 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition font-medium"
              >
                {language === 'ko' ? '문의하기' : 'Submit Inquiry'}
              </Link>
            </div>
          )}

          {/* Inquiries List */}
          {!loading && inquiries.length > 0 && (
            <div className="space-y-4">
              {inquiries.map((inquiry) => (
                <Link
                  key={inquiry.id}
                  href={`/my-inquiries/${inquiry.id}`}
                  className="block bg-white rounded-xl shadow hover:shadow-md transition p-5"
                >
                  <div className="flex items-start justify-between gap-4">
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-2">
                        <span className="text-xs px-2 py-0.5 bg-gray-100 text-gray-600 rounded">
                          {getCategoryLabel(inquiry.category || 'general')}
                        </span>
                        {getStatusBadge(inquiry.status)}
                      </div>
                      <h3 className="font-semibold text-gray-800 truncate">
                        {inquiry.subject || (language === 'ko' ? '제목 없음' : 'No subject')}
                      </h3>
                      <p className="text-sm text-gray-500 mt-1 line-clamp-2">
                        {inquiry.message}
                      </p>
                    </div>
                    <div className="text-right flex-shrink-0">
                      <p className="text-xs text-gray-400">
                        {formatDate(inquiry.created_at)}
                      </p>
                      {inquiry.admin_response && (
                        <span className="inline-block mt-2 text-xs px-2 py-1 bg-green-50 text-green-600 rounded">
                          {language === 'ko' ? '답변 있음' : 'Replied'}
                        </span>
                      )}
                    </div>
                  </div>
                </Link>
              ))}
            </div>
          )}

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex justify-center gap-2 mt-8">
              <button
                onClick={() => setPage(Math.max(1, page - 1))}
                disabled={page === 1}
                className="px-4 py-2 border rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
              >
                {language === 'ko' ? '이전' : 'Previous'}
              </button>
              <span className="px-4 py-2 text-gray-600">
                {page} / {totalPages}
              </span>
              <button
                onClick={() => setPage(Math.min(totalPages, page + 1))}
                disabled={page === totalPages}
                className="px-4 py-2 border rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
              >
                {language === 'ko' ? '다음' : 'Next'}
              </button>
            </div>
          )}
        </div>
      </div>
    </SidebarLayout>
  );
}
