import { useState, useEffect } from 'react'
import { AlertCircle, Send, CheckCircle2, Upload, X, Globe } from 'lucide-react'
import { api } from '../utils/api'
import FormInput from '../components/FormInput'
import { useToast } from '../components/ToastContainer'

// ─── Bilingual translations ────────────────────────────────────
const T = {
  en: {
    pageTitle: 'Submit an Issue',
    pageSubtitle: 'Report issues, request corrections, or make suggestions. We\'ll track your submission and keep you updated.',
    yourInfo: 'Your Information',
    name: 'Name',
    namePlaceholder: 'Your full name',
    nameRequired: 'Name is required',
    email: 'Email',
    emailPlaceholder: 'your.email@example.com',
    emailRequired: 'Email is required',
    emailInvalid: 'Invalid email address',
    phone: 'Phone (Optional)',
    phonePlaceholder: '+966 5X XXX XXXX',
    teamQuestion: 'Which team should handle your issue?',
    selectTeam: 'Select a team',
    issueDetails: 'Issue Details',
    category: 'Category',
    categoryPlaceholder: 'e.g., Marketing, IT, Operations',
    type: 'Type',
    priority: 'Priority',
    title: 'Title',
    titlePlaceholder: 'Brief summary of the issue',
    titleRequired: 'Title is required',
    description: 'Description',
    descriptionPlaceholder: 'Provide detailed information about the issue...',
    descriptionRequired: 'Description is required',
    attachment: 'Attachment (Optional)',
    uploadPrompt: 'Click to upload a file (screenshots, documents, etc.)',
    submit: 'Submit Issue',
    submitting: 'Submitting...',
    submitFailed: 'Failed to submit issue. Please try again.',
    footerNote: 'You\'ll receive a tracking link to monitor the progress of your issue.',
    // Success page
    successTitle: 'Issue Submitted Successfully!',
    successMessage: 'Thank you for submitting your issue. You can track its progress using the link below.',
    trackingLink: 'Your Tracking Link',
    copy: 'Copy',
    copied: 'Copied to clipboard!',
    trackIssue: 'Track Your Issue',
    submitAnother: 'Submit Another Issue',
    // Options
    request: 'Request', correction: 'Correction', complaint: 'Complaint', suggestion: 'Suggestion', other: 'Other',
    low: 'Low', medium: 'Medium', high: 'High', urgent: 'Urgent',
  },
  ar: {
    pageTitle: 'تقديم مشكلة',
    pageSubtitle: 'أبلغ عن مشاكل، اطلب تصحيحات، أو قدّم اقتراحات. سنتابع طلبك ونبقيك على اطلاع.',
    yourInfo: 'معلوماتك',
    name: 'الاسم',
    namePlaceholder: 'الاسم الكامل',
    nameRequired: 'الاسم مطلوب',
    email: 'البريد الإلكتروني',
    emailPlaceholder: 'your.email@example.com',
    emailRequired: 'البريد الإلكتروني مطلوب',
    emailInvalid: 'بريد إلكتروني غير صالح',
    phone: 'الهاتف (اختياري)',
    phonePlaceholder: '+966 5X XXX XXXX',
    teamQuestion: 'أي فريق يجب أن يتعامل مع مشكلتك؟',
    selectTeam: 'اختر فريقاً',
    issueDetails: 'تفاصيل المشكلة',
    category: 'الفئة',
    categoryPlaceholder: 'مثال: تسويق، تقنية، عمليات',
    type: 'النوع',
    priority: 'الأولوية',
    title: 'العنوان',
    titlePlaceholder: 'ملخص موجز للمشكلة',
    titleRequired: 'العنوان مطلوب',
    description: 'الوصف',
    descriptionPlaceholder: 'قدّم معلومات مفصلة عن المشكلة...',
    descriptionRequired: 'الوصف مطلوب',
    attachment: 'مرفق (اختياري)',
    uploadPrompt: 'اضغط لرفع ملف (لقطات شاشة، مستندات، إلخ)',
    submit: 'تقديم المشكلة',
    submitting: 'جارٍ التقديم...',
    submitFailed: 'فشل في تقديم المشكلة. يرجى المحاولة مرة أخرى.',
    footerNote: 'ستتلقى رابط تتبع لمراقبة تقدم مشكلتك.',
    successTitle: 'تم تقديم المشكلة بنجاح!',
    successMessage: 'شكراً لتقديم مشكلتك. يمكنك تتبع تقدمها من خلال الرابط أدناه.',
    trackingLink: 'رابط التتبع',
    copy: 'نسخ',
    copied: 'تم النسخ!',
    trackIssue: 'تتبع مشكلتك',
    submitAnother: 'تقديم مشكلة أخرى',
    request: 'طلب', correction: 'تصحيح', complaint: 'شكوى', suggestion: 'اقتراح', other: 'أخرى',
    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 PublicIssueSubmit() {
  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 TYPE_OPTIONS = [
    { value: 'request', label: t('request') },
    { value: 'correction', label: t('correction') },
    { value: 'complaint', label: t('complaint') },
    { value: 'suggestion', label: t('suggestion') },
    { value: 'other', label: t('other') },
  ]

  const PRIORITY_OPTIONS = [
    { value: 'low', label: t('low') },
    { value: 'medium', label: t('medium') },
    { value: 'high', label: t('high') },
    { value: 'urgent', label: t('urgent') },
  ]

  const urlParams = new URLSearchParams(window.location.search)
  const teamParam = urlParams.get('team')

  const [form, setForm] = useState({
    name: '', email: '', phone: '', category: 'Marketing',
    type: 'request', priority: 'medium', title: '', description: '', team_id: teamParam || '',
  })
  const [file, setFile] = useState(null)
  const [submitting, setSubmitting] = useState(false)
  const [submitted, setSubmitted] = useState(false)
  const [trackingToken, setTrackingToken] = useState('')
  const [errors, setErrors] = useState({})
  const [teams, setTeams] = useState([])

  useEffect(() => {
    if (!teamParam) {
      api.get('/public/teams').then(r => setTeams(Array.isArray(r) ? r : [])).catch(() => {})
    }
  }, [])

  const updateForm = (field, value) => {
    setForm((f) => ({ ...f, [field]: value }))
    if (errors[field]) setErrors((e) => ({ ...e, [field]: '' }))
  }

  const validate = () => {
    const newErrors = {}
    if (!form.name.trim()) newErrors.name = t('nameRequired')
    if (!form.email.trim()) newErrors.email = t('emailRequired')
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) newErrors.email = t('emailInvalid')
    if (!form.title.trim()) newErrors.title = t('titleRequired')
    if (!form.description.trim()) newErrors.description = t('descriptionRequired')
    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    if (!validate() || submitting) return
    try {
      setSubmitting(true)
      const formData = new FormData()
      formData.append('name', form.name)
      formData.append('email', form.email)
      formData.append('phone', form.phone)
      formData.append('category', form.category)
      formData.append('type', form.type)
      formData.append('priority', form.priority)
      formData.append('title', form.title)
      formData.append('description', form.description)
      if (form.team_id) formData.append('team_id', form.team_id)
      if (file) formData.append('file', file)
      const result = await api.upload('/public/issues', formData)
      setTrackingToken(result.token)
      setSubmitted(true)
    } catch (err) {
      console.error('Submit error:', err)
      toast.error(t('submitFailed'))
    } finally {
      setSubmitting(false)
    }
  }

  if (submitted) {
    const trackingUrl = `${window.location.origin}/track/${trackingToken}`
    return (
      <div className="min-h-screen bg-surface-secondary py-8 px-4" dir={dir}>
        <LangToggle lang={lang} setLang={setLang} />
        <div className="max-w-lg mx-auto bg-surface rounded-xl border border-border p-6">
          <div className="text-center">
            <div className="w-16 h-16 bg-emerald-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <CheckCircle2 className="w-10 h-10 text-emerald-600" />
            </div>
            <h1 className="text-2xl font-bold text-text-primary mb-2">{t('successTitle')}</h1>
            <p className="text-sm text-text-tertiary mb-6">{t('successMessage')}</p>

            <div className="bg-surface-secondary rounded-lg p-4 mb-6">
              <label className="block text-xs font-semibold text-text-tertiary uppercase mb-2">{t('trackingLink')}</label>
              <div className="flex gap-2">
                <input type="text" value={trackingUrl} readOnly
                  className="flex-1 px-3 py-2 text-sm border border-border rounded-lg bg-surface text-text-primary focus:outline-none" dir="ltr" />
                <button onClick={() => { navigator.clipboard.writeText(trackingUrl); toast.success(t('copied')) }}
                  className="px-4 py-2 bg-brand-primary text-white rounded-lg font-medium hover:bg-brand-primary-light transition-colors">
                  {t('copy')}
                </button>
              </div>
            </div>

            <div className="space-y-2">
              <a href={`/track/${trackingToken}`}
                className="block w-full px-4 py-2 bg-brand-primary text-white rounded-lg font-medium hover:bg-brand-primary-light transition-colors">
                {t('trackIssue')}
              </a>
              <button onClick={() => {
                setSubmitted(false); setTrackingToken('')
                setForm({ name: '', email: '', phone: '', category: 'Marketing', type: 'request', priority: 'medium', title: '', description: '', team_id: teamParam || '' })
                setFile(null)
              }}
                className="block w-full px-3 py-1.5 border border-border text-text-secondary rounded-lg hover:bg-surface-tertiary transition-colors">
                {t('submitAnother')}
              </button>
            </div>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-surface-secondary py-8 px-4" dir={dir}>
      <LangToggle lang={lang} setLang={setLang} />
      <div className="max-w-lg mx-auto bg-surface rounded-xl border border-border p-6">
        {/* Header */}
        <div className="text-center mb-6">
          <div className="w-12 h-12 bg-brand-primary/10 rounded-full flex items-center justify-center mx-auto mb-3">
            <AlertCircle className="w-6 h-6 text-brand-primary" />
          </div>
          <h1 className="text-2xl font-bold text-text-primary mb-2">{t('pageTitle')}</h1>
          <p className="text-sm text-text-tertiary">{t('pageSubtitle')}</p>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="space-y-4">
          {/* Contact Information */}
          <div>
            <h2 className="text-sm font-semibold text-text-primary mb-2">{t('yourInfo')}</h2>
            <div className="space-y-3">
              <FormInput label={t('name')} value={form.name} onChange={(e) => updateForm('name', e.target.value)}
                placeholder={t('namePlaceholder')} required error={errors.name} />
              <FormInput label={t('email')} type="email" value={form.email} onChange={(e) => updateForm('email', e.target.value)}
                placeholder={t('emailPlaceholder')} required error={errors.email} />
              <FormInput label={t('phone')} value={form.phone} onChange={(e) => updateForm('phone', e.target.value)}
                placeholder={t('phonePlaceholder')} />
            </div>
          </div>

          {/* Team Selection */}
          {!teamParam && teams.length > 0 && (
            <div>
              <h2 className="text-sm font-semibold text-text-primary mb-2">{t('teamQuestion')}</h2>
              <select value={form.team_id} onChange={(e) => updateForm('team_id', e.target.value)}
                className="w-full px-3 py-2 text-sm border border-border rounded-lg bg-surface text-text-primary focus:outline-none focus:ring-2 focus:ring-brand-primary/20 transition-colors">
                <option value="">{t('selectTeam')}</option>
                {teams.map((team) => <option key={team.id} value={team.id}>{team.name}</option>)}
              </select>
            </div>
          )}

          {/* Issue Details */}
          <div>
            <h2 className="text-sm font-semibold text-text-primary mb-2">{t('issueDetails')}</h2>
            <div className="space-y-3">
              <div>
                <label className="block text-sm font-medium text-text-primary mb-1.5">
                  {t('category')} <span className="text-red-500">*</span>
                </label>
                <input type="text" value={form.category} onChange={(e) => updateForm('category', e.target.value)}
                  placeholder={t('categoryPlaceholder')}
                  className="w-full px-3 py-2 text-sm border border-border rounded-lg bg-surface text-text-primary focus:outline-none focus:ring-2 focus:ring-brand-primary/20 transition-colors" />
              </div>

              <div>
                <label className="block text-sm font-medium text-text-primary mb-1.5">
                  {t('type')} <span className="text-red-500">*</span>
                </label>
                <select value={form.type} onChange={(e) => updateForm('type', e.target.value)}
                  className="w-full px-3 py-2 text-sm border border-border rounded-lg bg-surface text-text-primary focus:outline-none focus:ring-2 focus:ring-brand-primary/20 transition-colors">
                  {TYPE_OPTIONS.map((opt) => <option key={opt.value} value={opt.value}>{opt.label}</option>)}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-text-primary mb-1.5">
                  {t('priority')} <span className="text-red-500">*</span>
                </label>
                <select value={form.priority} onChange={(e) => updateForm('priority', e.target.value)}
                  className="w-full px-3 py-2 text-sm border border-border rounded-lg bg-surface text-text-primary focus:outline-none focus:ring-2 focus:ring-brand-primary/20 transition-colors">
                  {PRIORITY_OPTIONS.map((opt) => <option key={opt.value} value={opt.value}>{opt.label}</option>)}
                </select>
              </div>

              <FormInput label={t('title')} value={form.title} onChange={(e) => updateForm('title', e.target.value)}
                placeholder={t('titlePlaceholder')} required error={errors.title} />
              <FormInput label={t('description')} type="textarea" value={form.description}
                onChange={(e) => updateForm('description', e.target.value)}
                placeholder={t('descriptionPlaceholder')} rows={6} required error={errors.description} />
            </div>
          </div>

          {/* File Upload */}
          <div>
            <h2 className="text-sm font-semibold text-text-primary mb-2">{t('attachment')}</h2>
            <label className="block cursor-pointer">
              <input type="file" onChange={(e) => { if (e.target.files?.[0]) setFile(e.target.files[0]) }} className="hidden" />
              <div className="border-2 border-dashed border-border rounded-lg p-4 text-center hover:bg-surface-secondary/50 transition-colors">
                <Upload className="w-6 h-6 mx-auto mb-2 text-text-tertiary" />
                {file ? (
                  <div className="flex items-center justify-center gap-2">
                    <p className="text-sm text-text-primary font-medium">{file.name}</p>
                    <button type="button" onClick={(e) => { e.stopPropagation(); setFile(null) }} className="p-1 hover:bg-surface-tertiary rounded">
                      <X className="w-4 h-4 text-red-600" />
                    </button>
                  </div>
                ) : (
                  <p className="text-sm text-text-tertiary">{t('uploadPrompt')}</p>
                )}
              </div>
            </label>
          </div>

          {/* Submit */}
          <button type="submit" disabled={submitting}
            className="w-full px-4 py-2 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 justify-center gap-2">
            {submitting ? (
              <>
                <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                {t('submitting')}
              </>
            ) : (
              <>
                <Send className="w-5 h-5" />
                {t('submit')}
              </>
            )}
          </button>
        </form>

        <p className="text-xs text-text-tertiary text-center mt-4">{t('footerNote')}</p>
      </div>
    </div>
  )
}
