'use client';

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

export default function InquiryDetailPage() {
  const { language } = useTranslation();
  const { user } = useAuthStore();
  const router = useRouter();
  const params = useParams();
  const inquiryId = Number(params.id);

  const [inquiry, setInquiry] = useState<InquiryWithMessages | null>(null);
  const [loading, setLoading] = useState(true);
  const [newMessage, setNewMessage] = useState('');
  const [sending, setSending] = useState(false);

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

    if (inquiryId) {
      fetchInquiry();
    }
  }, [user, router, inquiryId]);

  const fetchInquiry = async () => {
    try {
      setLoading(true);
      const data = await inquiryApi.getInquiryDetail(inquiryId);
      setInquiry(data);
    } catch (error) {
      console.error('Failed to fetch inquiry:', error);
      router.push('/my-inquiries');
    } finally {
      setLoading(false);
    }
  };

  const handleSendMessage = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newMessage.trim()) return;

    setSending(true);
    try {
      const message = await inquiryApi.addMessage(inquiryId, newMessage);
      setInquiry((prev) => {
        if (!prev) return prev;
        return {
          ...prev,
          messages: [...prev.messages, message],
        };
      });
      setNewMessage('');
    } catch (error: any) {
      alert(error.response?.data?.detail || (language === 'ko' ? '메시지 전송 실패' : 'Failed to send message'));
    } finally {
      setSending(false);
    }
  };

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

  const formatDateTime = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleString(language === 'ko' ? 'ko-KR' : 'en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  if (!user) return null;

  if (loading) {
    return (
      <SidebarLayout groupKey="inquiry">
        <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>
      </SidebarLayout>
    );
  }

  if (!inquiry) {
    return (
      <SidebarLayout groupKey="inquiry">
        <div className="text-center py-12">
          <p className="text-gray-500">{language === 'ko' ? '문의를 찾을 수 없습니다' : 'Inquiry not found'}</p>
        </div>
      </SidebarLayout>
    );
  }

  return (
    <SidebarLayout groupKey="inquiry">
      <div className="container mx-auto">
        <div className="max-w-3xl mx-auto">
          {/* Back Button */}
          <Link
            href="/my-inquiries"
            className="inline-flex items-center text-gray-600 hover:text-gray-800 mb-4"
          >
            <svg className="w-5 h-5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
            </svg>
            {language === 'ko' ? '목록으로' : 'Back to list'}
          </Link>

          {/* Inquiry Header */}
          <div className="bg-white rounded-xl shadow-lg p-6 mb-6">
            <div className="flex items-start justify-between gap-4 mb-4">
              <div className="flex-1">
                <h1 className="text-xl font-bold text-gray-800">
                  {inquiry.inquiry.subject || (language === 'ko' ? '제목 없음' : 'No subject')}
                </h1>
                <p className="text-sm text-gray-500 mt-1">
                  {formatDateTime(inquiry.inquiry.created_at)}
                </p>
              </div>
              {getStatusBadge(inquiry.inquiry.status)}
            </div>

            <div className="border-t pt-4">
              <p className="text-gray-700 whitespace-pre-wrap">{inquiry.inquiry.message}</p>
            </div>
          </div>

          {/* Messages Thread */}
          <div className="bg-white rounded-xl shadow-lg overflow-hidden">
            <div className="p-4 bg-gray-50 border-b">
              <h2 className="font-semibold text-gray-800">
                {language === 'ko' ? '대화 내역' : 'Conversation'}
                {inquiry.messages.length > 0 && ` (${inquiry.messages.length})`}
              </h2>
            </div>

            {/* Messages */}
            <div className="p-4 space-y-4 max-h-[400px] overflow-y-auto">
              {inquiry.messages.length === 0 ? (
                <div className="text-center py-8 text-gray-500">
                  <div className="text-4xl mb-2">💬</div>
                  <p>{language === 'ko' ? '아직 답변이 없습니다' : 'No replies yet'}</p>
                </div>
              ) : (
                inquiry.messages.map((msg) => (
                  <div
                    key={msg.id}
                    className={`flex ${msg.is_admin ? 'justify-start' : 'justify-end'}`}
                  >
                    <div
                      className={`max-w-[80%] rounded-lg p-4 ${
                        msg.is_admin
                          ? 'bg-gray-100 text-gray-800'
                          : 'bg-primary-600 text-white'
                      }`}
                    >
                      <div className="flex items-center gap-2 mb-1">
                        <span className="font-medium text-sm">
                          {msg.is_admin
                            ? (language === 'ko' ? '관리자' : 'Admin')
                            : (language === 'ko' ? '나' : 'Me')}
                        </span>
                        <span className={`text-xs ${msg.is_admin ? 'text-gray-500' : 'text-primary-200'}`}>
                          {formatDateTime(msg.created_at)}
                        </span>
                      </div>
                      <p className="whitespace-pre-wrap">{msg.message}</p>
                    </div>
                  </div>
                ))
              )}
            </div>

            {/* Reply Form */}
            {inquiry.inquiry.status !== 'closed' && (
              <div className="p-4 border-t bg-gray-50">
                <form onSubmit={handleSendMessage} className="flex gap-3">
                  <input
                    type="text"
                    value={newMessage}
                    onChange={(e) => setNewMessage(e.target.value)}
                    placeholder={language === 'ko' ? '메시지를 입력하세요...' : 'Type your message...'}
                    className="flex-1 px-4 py-2 border rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                  />
                  <button
                    type="submit"
                    disabled={sending || !newMessage.trim()}
                    className="px-6 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition disabled:opacity-50 font-medium"
                  >
                    {sending
                      ? (language === 'ko' ? '전송중...' : 'Sending...')
                      : (language === 'ko' ? '전송' : 'Send')}
                  </button>
                </form>
              </div>
            )}

            {inquiry.inquiry.status === 'closed' && (
              <div className="p-4 border-t bg-gray-100 text-center text-gray-500">
                {language === 'ko' ? '이 문의는 종료되었습니다' : 'This inquiry is closed'}
              </div>
            )}
          </div>
        </div>
      </div>
    </SidebarLayout>
  );
}
