'use client';

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

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

  const [category, setCategory] = useState('general');
  const [subject, setSubject] = useState('');
  const [message, setMessage] = useState('');
  const [contactEmail, setContactEmail] = useState('');
  const [contactPhone, setContactPhone] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [success, setSuccess] = useState(false);

  useEffect(() => {
    if (!user) {
      router.push('/login?redirect=/inquiry');
    } else {
      setContactEmail(user.email || '');
    }
  }, [user, router]);

  const categories = [
    { value: 'general', label: { ko: '일반 문의', en: 'General', mn: 'Ерөнхий', ru: 'Общий' } },
    { value: 'vehicle', label: { ko: '차량 관련', en: 'Vehicle', mn: 'Машин', ru: 'Авто' } },
    { value: 'payment', label: { ko: '결제/충전', en: 'Payment', mn: 'Төлбөр', ru: 'Оплата' } },
    { value: 'shipping', label: { ko: '배송', en: 'Shipping', mn: 'Хүргэлт', ru: 'Доставка' } },
    { value: 'account', label: { ko: '계정', en: 'Account', mn: 'Бүртгэл', ru: 'Аккаунт' } },
    { value: 'other', label: { ko: '기타', en: 'Other', mn: 'Бусад', ru: 'Другое' } },
  ];

  const getLabel = (labelObj: { ko: string; en: string; mn: string; ru: string }) => {
    return labelObj[language as keyof typeof labelObj] || labelObj.en;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!subject.trim() || !message.trim()) {
      alert(language === 'ko' ? '제목과 내용을 입력해주세요' : 'Please enter subject and message');
      return;
    }

    setSubmitting(true);
    try {
      await inquiryApi.createInquiry({
        category,
        subject,
        message,
        contact_email: contactEmail,
        contact_phone: contactPhone,
      });
      setSuccess(true);
      setSubject('');
      setMessage('');
      setCategory('general');
    } catch (error: any) {
      alert(error.response?.data?.detail || (language === 'ko' ? '문의 제출에 실패했습니다' : 'Failed to submit inquiry'));
    } finally {
      setSubmitting(false);
    }
  };

  if (!user) {
    return null;
  }

  return (
    <SidebarLayout groupKey="inquiry">
      <div className="container mx-auto">
        <div className="max-w-2xl mx-auto">
          {/* Header */}
          <div className="mb-6">
            <h1 className="text-2xl font-bold text-gray-800">
              {language === 'ko' ? '문의하기' : language === 'mn' ? 'Асуулт илгээх' : language === 'ru' ? 'Отправить запрос' : 'New Inquiry'}
            </h1>
            <p className="text-gray-600">
              {language === 'ko' ? '궁금한 점을 문의해주세요' : 'Submit your question or concern'}
            </p>
          </div>

          {/* Success Message */}
          {success && (
            <div className="bg-green-50 border border-green-200 rounded-xl p-6 mb-6">
              <div className="flex items-start gap-4">
                <span className="text-3xl">✓</span>
                <div>
                  <h3 className="font-semibold text-green-800">
                    {language === 'ko' ? '문의가 접수되었습니다!' : 'Inquiry Submitted!'}
                  </h3>
                  <p className="text-green-600 text-sm mt-1">
                    {language === 'ko'
                      ? '빠른 시일 내에 답변 드리겠습니다.'
                      : 'We will respond as soon as possible.'}
                  </p>
                  <button
                    onClick={() => router.push('/my-inquiries')}
                    className="mt-3 text-sm text-green-700 hover:underline"
                  >
                    {language === 'ko' ? '내 문의 목록 보기 →' : 'View my inquiries →'}
                  </button>
                </div>
              </div>
            </div>
          )}

          {/* Inquiry Form */}
          <div className="bg-white rounded-xl shadow-lg p-6">
            <form onSubmit={handleSubmit} className="space-y-5">
              {/* Category */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  {language === 'ko' ? '문의 유형' : 'Category'}
                </label>
                <div className="grid grid-cols-3 gap-2">
                  {categories.map((cat) => (
                    <button
                      key={cat.value}
                      type="button"
                      onClick={() => setCategory(cat.value)}
                      className={`py-2 px-3 border rounded-lg text-sm transition-colors ${
                        category === cat.value
                          ? 'border-primary-500 bg-primary-50 text-primary-700'
                          : 'border-gray-200 hover:border-gray-300 text-gray-600'
                      }`}
                    >
                      {getLabel(cat.label)}
                    </button>
                  ))}
                </div>
              </div>

              {/* Subject */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {language === 'ko' ? '제목' : 'Subject'} *
                </label>
                <input
                  type="text"
                  value={subject}
                  onChange={(e) => setSubject(e.target.value)}
                  placeholder={language === 'ko' ? '문의 제목을 입력하세요' : 'Enter inquiry subject'}
                  className="w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                  required
                />
              </div>

              {/* Message */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {language === 'ko' ? '문의 내용' : 'Message'} *
                </label>
                <textarea
                  value={message}
                  onChange={(e) => setMessage(e.target.value)}
                  placeholder={language === 'ko' ? '문의 내용을 상세히 입력해주세요' : 'Please describe your inquiry in detail'}
                  rows={6}
                  className="w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 resize-none"
                  required
                />
              </div>

              {/* Contact Info */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {language === 'ko' ? '연락 이메일' : 'Contact Email'}
                  </label>
                  <input
                    type="email"
                    value={contactEmail}
                    onChange={(e) => setContactEmail(e.target.value)}
                    placeholder="email@example.com"
                    className="w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {language === 'ko' ? '연락 전화번호' : 'Contact Phone'}
                  </label>
                  <input
                    type="tel"
                    value={contactPhone}
                    onChange={(e) => setContactPhone(e.target.value)}
                    placeholder={language === 'ko' ? '전화번호 (선택)' : 'Phone number (optional)'}
                    className="w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                  />
                </div>
              </div>

              {/* Submit Button */}
              <button
                type="submit"
                disabled={submitting}
                className="w-full py-3 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition font-semibold disabled:opacity-50"
              >
                {submitting
                  ? (language === 'ko' ? '제출 중...' : 'Submitting...')
                  : (language === 'ko' ? '문의 제출' : 'Submit Inquiry')}
              </button>
            </form>
          </div>

          {/* Info */}
          <div className="mt-6 bg-blue-50 border border-blue-200 rounded-lg p-4">
            <div className="flex items-start gap-3">
              <span className="text-xl">💡</span>
              <div className="text-sm text-blue-700">
                <p className="font-medium mb-1">
                  {language === 'ko' ? '답변 안내' : 'Response Info'}
                </p>
                <ul className="list-disc list-inside space-y-1">
                  <li>{language === 'ko' ? '영업일 기준 1-2일 내 답변 드립니다' : 'We will respond within 1-2 business days'}</li>
                  <li>{language === 'ko' ? '긴급 문의는 카카오톡을 이용해주세요' : 'For urgent inquiries, please use KakaoTalk'}</li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>
    </SidebarLayout>
  );
}
