import { useState, useEffect } from 'react'
import { useParams } from 'react-router-dom'
import { AlertCircle, Clock, CheckCircle2, XCircle, MessageCircle, Upload, FileText, Send, Globe } from 'lucide-react'
import { api } from '../utils/api'
import { useToast } from '../components/ToastContainer'

// ─── Bilingual translations ────────────────────────────────────
const T = {
  en: {
    description: 'Description',
    submitted: 'Submitted',
    lastUpdated: 'Last Updated',
    resolution: 'Resolution',
    declined: 'Declined',
    progressUpdates: 'Progress Updates',
    noUpdates: 'No updates yet. We\'ll post updates here as we work on your issue.',
    team: 'Team', you: 'You',
    attachments: 'Attachments',
    download: 'Download',
    addComment: 'Add a Comment',
    yourName: 'Your Name (Optional)',
    yourNamePlaceholder: 'Your name',
    message: 'Message',
    messagePlaceholder: 'Add additional information or ask a question...',
    sendComment: 'Send Comment',
    sending: 'Sending...',
    uploadFile: 'Upload File',
    uploading: 'Uploading...',
    bookmarkNote: 'Bookmark this page to check your issue status anytime.',
    notFoundTitle: 'Issue Not Found',
    notFoundMessage: 'The tracking link you used is invalid or the issue has been removed.',
    submitNew: 'Submit a New Issue',
    failedComment: 'Failed to add comment',
    failedUpload: 'Failed to upload file',
    priority: 'Priority',
    // Status
    new: 'New', acknowledged: 'Acknowledged', in_progress: 'In Progress', resolved: 'Resolved', declined_status: 'Declined',
    // Priority
    low: 'Low', medium: 'Medium', high: 'High', urgent: 'Urgent',
  },
  ar: {
    description: 'الوصف',
    submitted: 'تم التقديم',
    lastUpdated: 'آخر تحديث',
    resolution: 'الحل',
    declined: 'مرفوض',
    progressUpdates: 'تحديثات التقدم',
    noUpdates: 'لا توجد تحديثات بعد. سننشر التحديثات هنا أثناء العمل على مشكلتك.',
    team: 'الفريق', you: 'أنت',
    attachments: 'المرفقات',
    download: 'تحميل',
    addComment: 'إضافة تعليق',
    yourName: 'اسمك (اختياري)',
    yourNamePlaceholder: 'اسمك',
    message: 'الرسالة',
    messagePlaceholder: 'أضف معلومات إضافية أو اطرح سؤالاً...',
    sendComment: 'إرسال التعليق',
    sending: 'جارٍ الإرسال...',
    uploadFile: 'رفع ملف',
    uploading: 'جارٍ الرفع...',
    bookmarkNote: 'احفظ هذه الصفحة للاطلاع على حالة مشكلتك في أي وقت.',
    notFoundTitle: 'المشكلة غير موجودة',
    notFoundMessage: 'رابط التتبع الذي استخدمته غير صالح أو تمت إزالة المشكلة.',
    submitNew: 'تقديم مشكلة جديدة',
    failedComment: 'فشل في إضافة التعليق',
    failedUpload: 'فشل في رفع الملف',
    priority: 'الأولوية',
    new: 'جديد', acknowledged: 'تم الاستلام', in_progress: 'قيد التنفيذ', resolved: 'تم الحل', declined_status: 'مرفوض',
    low: 'منخفضة', medium: 'متوسطة', high: 'عالية', urgent: 'عاجلة',
  },
}

function detectLang() {
  const nav = navigator.language || navigator.userLanguage || ''
  return nav.startsWith('ar') ? 'ar' : 'en'
}

function LangToggle({ lang, setLang }) {
  return (
    <button
      onClick={() => setLang(lang === 'en' ? 'ar' : 'en')}
      className="fixed top-4 end-4 z-50 flex items-center gap-1.5 px-3 py-1.5 bg-surface border border-border rounded-full shadow-sm hover:bg-surface-secondary transition-colors text-sm font-medium text-text-primary"
    >
      <Globe className="w-4 h-4" />
      {lang === 'en' ? 'العربية' : 'English'}
    </button>
  )
}

export default function PublicIssueTracker() {
  const { token } = useParams()
  const toast = useToast()
  const [lang, setLang] = useState(detectLang)
  const t = (key) => T[lang]?.[key] || T.en[key] || key
  const dir = lang === 'ar' ? 'rtl' : 'ltr'

  useEffect(() => {
    document.documentElement.dir = dir
    document.documentElement.lang = lang
    return () => { document.documentElement.dir = 'ltr'; document.documentElement.lang = 'en' }
  }, [lang, dir])

  const [issue, setIssue] = useState(null)
  const [updates, setUpdates] = useState([])
  const [attachments, setAttachments] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)
  const [commentName, setCommentName] = useState('')
  const [commentMessage, setCommentMessage] = useState('')
  const [submittingComment, setSubmittingComment] = useState(false)
  const [uploadingFile, setUploadingFile] = useState(false)

  useEffect(() => { loadIssue() }, [token])

  const loadIssue = async () => {
    try {
      setLoading(true); setError(null)
      const data = await api.get(`/public/issues/${token}`)
      setIssue(data.issue)
      setUpdates(data.updates || [])
      setAttachments(data.attachments || [])
    } catch (err) {
      setError(err.response?.status === 404 ? 'notFound' : 'error')
    } finally {
      setLoading(false)
    }
  }

  const handleAddComment = async (e) => {
    e.preventDefault()
    if (!commentMessage.trim() || submittingComment) return
    try {
      setSubmittingComment(true)
      await api.post(`/public/issues/${token}/comment`, { name: commentName.trim() || 'Anonymous', message: commentMessage })
      setCommentMessage('')
      await loadIssue()
    } catch { toast.error(t('failedComment')) }
    finally { setSubmittingComment(false) }
  }

  const handleFileUpload = async (e) => {
    const file = e.target.files?.[0]
    if (!file) return
    try {
      setUploadingFile(true)
      const formData = new FormData()
      formData.append('file', file)
      formData.append('name', commentName.trim() || 'Anonymous')
      await api.upload(`/public/issues/${token}/attachments`, formData)
      await loadIssue()
      e.target.value = ''
    } catch { toast.error(t('failedUpload')) }
    finally { setUploadingFile(false) }
  }

  const dateFmt = (dateStr) => {
    if (!dateStr) return ''
    return new Date(dateStr).toLocaleDateString(lang === 'ar' ? 'ar-SA' : 'en-US', { month: 'long', day: 'numeric', year: 'numeric' })
  }

  const dateTimeFmt = (dateStr) => {
    if (!dateStr) return ''
    return new Date(dateStr).toLocaleString(lang === 'ar' ? 'ar-SA' : 'en-US', { month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit' })
  }

  const fileSize = (bytes) => {
    if (bytes < 1024) return bytes + ' B'
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
    return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
  }

  const STATUS_CONFIG = {
    new: { label: t('new'), bg: 'bg-purple-100', text: 'text-purple-700', dot: 'bg-purple-500', icon: AlertCircle },
    acknowledged: { label: t('acknowledged'), bg: 'bg-blue-100', text: 'text-blue-700', dot: 'bg-blue-500', icon: CheckCircle2 },
    in_progress: { label: t('in_progress'), bg: 'bg-amber-100', text: 'text-amber-700', dot: 'bg-amber-500', icon: Clock },
    resolved: { label: t('resolved'), bg: 'bg-emerald-100', text: 'text-emerald-700', dot: 'bg-emerald-500', icon: CheckCircle2 },
    declined: { label: t('declined_status'), bg: 'bg-gray-100', text: 'text-gray-700', dot: 'bg-gray-500', icon: XCircle },
  }

  const PRIORITY_CONFIG = {
    low: { label: t('low'), color: 'text-gray-700' },
    medium: { label: t('medium'), color: 'text-blue-700' },
    high: { label: t('high'), color: 'text-orange-700' },
    urgent: { label: t('urgent'), color: 'text-red-700' },
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-surface-secondary py-8 px-4" dir={dir}>
        <LangToggle lang={lang} setLang={setLang} />
        <div className="max-w-2xl mx-auto space-y-6 animate-pulse">
          <div className="bg-surface rounded-xl border border-border p-6 space-y-4">
            <div className="h-5 bg-surface-tertiary rounded w-24" />
            <div className="h-7 bg-surface-tertiary rounded w-3/4" />
            <div className="h-4 bg-surface-tertiary rounded w-full" />
            <div className="h-4 bg-surface-tertiary rounded w-2/3" />
          </div>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="min-h-screen bg-surface-secondary py-8 px-4" dir={dir}>
        <LangToggle lang={lang} setLang={setLang} />
        <div className="max-w-md mx-auto bg-surface rounded-xl border border-border p-6 text-center">
          <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
            <XCircle className="w-10 h-10 text-red-600" />
          </div>
          <h1 className="text-2xl font-bold text-text-primary mb-2">{t('notFoundTitle')}</h1>
          <p className="text-sm text-text-tertiary mb-6">{t('notFoundMessage')}</p>
          <a href="/submit-issue" className="inline-block px-4 py-2 bg-brand-primary text-white rounded-lg font-medium hover:bg-brand-primary-light transition-colors">
            {t('submitNew')}
          </a>
        </div>
      </div>
    )
  }

  if (!issue) return null

  const statusConfig = STATUS_CONFIG[issue.status] || STATUS_CONFIG.new
  const priorityConfig = PRIORITY_CONFIG[issue.priority] || PRIORITY_CONFIG.medium

  return (
    <div className="min-h-screen bg-surface-secondary py-8 px-4" dir={dir}>
      <LangToggle lang={lang} setLang={setLang} />
      <div className="max-w-2xl mx-auto">
        {/* Header */}
        <div className="bg-surface rounded-xl border border-border p-6 mb-6">
          <div className="mb-4">
            <div className="flex items-center gap-2 mb-3">
              <span className={`text-xs px-2 py-1 rounded-full font-medium flex items-center gap-1.5 ${statusConfig.bg} ${statusConfig.text}`}>
                <span className={`w-1.5 h-1.5 rounded-full ${statusConfig.dot}`} />
                {statusConfig.label}
              </span>
              <span className={`text-xs font-medium ${priorityConfig.color}`}>
                {priorityConfig.label} {t('priority')}
              </span>
              <span className="text-xs text-text-tertiary">•</span>
              <span className="text-xs text-text-tertiary capitalize">{issue.type}</span>
            </div>
            <h1 className="text-2xl font-bold text-text-primary mb-2">{issue.title}</h1>
          </div>

          <div className="mb-4">
            <h2 className="text-sm font-semibold text-text-primary mb-2">{t('description')}</h2>
            <p className="text-sm text-text-tertiary whitespace-pre-wrap">{issue.description}</p>
          </div>

          <div className="grid grid-cols-2 gap-4 text-sm pt-4 border-t border-border">
            <div>
              <span className="text-text-tertiary">{t('submitted')}:</span>
              <span className="text-text-primary font-medium ms-2">{dateFmt(issue.created_at)}</span>
            </div>
            <div>
              <span className="text-text-tertiary">{t('lastUpdated')}:</span>
              <span className="text-text-primary font-medium ms-2">{dateFmt(issue.updated_at)}</span>
            </div>
          </div>
        </div>

        {/* Resolution Summary */}
        {(issue.status === 'resolved' || issue.status === 'declined') && issue.resolution_summary && (
          <div className={`rounded-2xl shadow-sm p-6 mb-6 ${issue.status === 'resolved' ? 'bg-emerald-50 border-2 border-emerald-200' : 'bg-gray-50 border-2 border-gray-200'}`}>
            <div className="flex items-start gap-3">
              {issue.status === 'resolved'
                ? <CheckCircle2 className="w-6 h-6 text-emerald-600 shrink-0 mt-1" />
                : <XCircle className="w-6 h-6 text-gray-600 shrink-0 mt-1" />}
              <div className="flex-1">
                <h2 className={`text-lg font-bold mb-2 ${issue.status === 'resolved' ? 'text-emerald-900' : 'text-gray-900'}`}>
                  {issue.status === 'resolved' ? t('resolution') : t('declined')}
                </h2>
                <p className={`${issue.status === 'resolved' ? 'text-emerald-800' : 'text-gray-800'} whitespace-pre-wrap`}>
                  {issue.resolution_summary}
                </p>
                {issue.resolved_at && (
                  <p className={`text-sm mt-2 ${issue.status === 'resolved' ? 'text-emerald-600' : 'text-gray-600'}`}>
                    {dateFmt(issue.resolved_at)}
                  </p>
                )}
              </div>
            </div>
          </div>
        )}

        {/* Progress Timeline */}
        <div className="bg-surface rounded-2xl shadow-sm p-8 mb-6">
          <h2 className="text-xl font-bold text-text-primary mb-6 flex items-center gap-2">
            <MessageCircle className="w-6 h-6" />
            {t('progressUpdates')}
          </h2>
          {updates.length === 0 ? (
            <div className="text-center py-12">
              <Clock className="w-12 h-12 text-text-tertiary mx-auto mb-3" />
              <p className="text-text-secondary">{t('noUpdates')}</p>
            </div>
          ) : (
            <div className="space-y-4">
              {updates.map((update, idx) => (
                <div key={update.Id || update.id || idx} className="border-s-4 border-brand-primary ps-4 py-2">
                  <div className="flex items-start justify-between gap-3 mb-2">
                    <div className="flex items-center gap-2">
                      <span className="font-semibold text-text-primary">{update.author_name}</span>
                      <span className={`text-xs px-2 py-0.5 rounded-full ${update.author_type === 'staff' ? 'bg-purple-100 text-purple-700' : 'bg-gray-200 text-gray-700'}`}>
                        {update.author_type === 'staff' ? t('team') : t('you')}
                      </span>
                    </div>
                    <span className="text-sm text-text-tertiary">{dateTimeFmt(update.created_at)}</span>
                  </div>
                  <p className="text-text-secondary whitespace-pre-wrap">{update.message}</p>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Attachments */}
        {attachments.length > 0 && (
          <div className="bg-surface rounded-2xl shadow-sm p-8 mb-6">
            <h2 className="text-xl font-bold text-text-primary mb-6 flex items-center gap-2">
              <FileText className="w-6 h-6" />
              {t('attachments')}
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
              {attachments.map((att) => (
                <div key={att.Id || att.id} className="flex items-center justify-between p-3 bg-surface-secondary rounded-lg">
                  <div className="flex items-center gap-3 flex-1 min-w-0">
                    <FileText className="w-5 h-5 text-text-tertiary shrink-0" />
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-text-primary truncate">{att.original_name}</p>
                      <p className="text-xs text-text-tertiary">{fileSize(att.size)} • {att.uploaded_by}</p>
                    </div>
                  </div>
                  <a href={`/api/uploads/${att.filename}`} target="_blank" rel="noopener noreferrer"
                    className="text-xs text-brand-primary hover:underline ms-2">
                    {t('download')}
                  </a>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Add Comment */}
        {issue.status !== 'resolved' && issue.status !== 'declined' && (
          <div className="bg-surface rounded-2xl shadow-sm p-8">
            <h2 className="text-xl font-bold text-text-primary mb-6 flex items-center gap-2">
              <MessageCircle className="w-6 h-6" />
              {t('addComment')}
            </h2>
            <form onSubmit={handleAddComment} className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-text-primary mb-2">{t('yourName')}</label>
                <input type="text" value={commentName} onChange={(e) => setCommentName(e.target.value)}
                  placeholder={t('yourNamePlaceholder')}
                  className="w-full px-4 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20" />
              </div>
              <div>
                <label className="block text-sm font-medium text-text-primary mb-2">
                  {t('message')} <span className="text-red-500">*</span>
                </label>
                <textarea value={commentMessage} onChange={(e) => setCommentMessage(e.target.value)}
                  placeholder={t('messagePlaceholder')} rows={4} required
                  className="w-full px-4 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20" />
              </div>
              <div className="flex gap-3">
                <button type="submit" disabled={!commentMessage.trim() || submittingComment}
                  className="px-6 py-3 bg-brand-primary text-white rounded-lg font-medium hover:bg-brand-primary-light disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center gap-2">
                  <Send className="w-4 h-4" />
                  {submittingComment ? t('sending') : t('sendComment')}
                </button>
                <label className="cursor-pointer">
                  <input type="file" onChange={handleFileUpload} disabled={uploadingFile} className="hidden" />
                  <div className="px-6 py-3 bg-surface-secondary text-text-primary rounded-lg font-medium hover:bg-surface-tertiary transition-colors flex items-center gap-2">
                    <Upload className="w-4 h-4" />
                    {uploadingFile ? t('uploading') : t('uploadFile')}
                  </div>
                </label>
              </div>
            </form>
          </div>
        )}

        {/* Footer */}
        <div className="text-center mt-8">
          <p className="text-sm text-text-tertiary">{t('bookmarkNote')}</p>
        </div>
      </div>
    </div>
  )
}
