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

const TYPE_OPTIONS = [
  { value: 'request', label: 'Request' },
  { value: 'correction', label: 'Correction' },
  { value: 'complaint', label: 'Complaint' },
  { value: 'suggestion', label: 'Suggestion' },
  { value: 'other', label: 'Other' },
]

const PRIORITY_OPTIONS = [
  { value: 'low', label: 'Low' },
  { value: 'medium', label: 'Medium' },
  { value: 'high', label: 'High' },
  { value: 'urgent', label: 'Urgent' },
]

export default function PublicIssueSubmit() {
  const toast = useToast()

  // Team pre-selection from URL
  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 handleFileChange = (e) => {
    const selectedFile = e.target.files?.[0]
    if (selectedFile) {
      setFile(selectedFile)
    }
  }

  const validate = () => {
    const newErrors = {}
    if (!form.name.trim()) newErrors.name = 'Name is required'
    if (!form.email.trim()) newErrors.email = 'Email is required'
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) newErrors.email = 'Invalid email address'
    if (!form.title.trim()) newErrors.title = 'Title is required'
    if (!form.description.trim()) newErrors.description = 'Description is required'
    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('Failed to submit issue. Please try again.')
    } 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">
        <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">Issue Submitted Successfully!</h1>
            <p className="text-sm text-text-tertiary mb-6">
              Thank you for submitting your issue. You can track its progress using the link below.
            </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">Your Tracking Link</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 focus:ring-2 focus:ring-brand-primary/20 transition-colors"
                />
                <button
                  onClick={() => {
                    navigator.clipboard.writeText(trackingUrl)
                    toast.success('Copied to clipboard!')
                  }}
                  className="px-4 py-2 bg-brand-primary text-white rounded-lg font-medium hover:bg-brand-primary-light transition-colors"
                >
                  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"
              >
                Track Your Issue
              </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"
              >
                Submit Another Issue
              </button>
            </div>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-surface-secondary py-8 px-4">
      <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">Submit an Issue</h1>
          <p className="text-sm text-text-tertiary">
            Report issues, request corrections, or make suggestions. We'll track your submission and keep you updated.
          </p>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="space-y-4">
          {/* Contact Information */}
          <div>
            <h2 className="text-sm font-semibold text-text-primary mb-2">Your Information</h2>
            <div className="space-y-3">
              <FormInput
                label="Name"
                value={form.name}
                onChange={(e) => updateForm('name', e.target.value)}
                placeholder="Your full name"
                required
                error={errors.name}
              />
              <FormInput
                label="Email"
                type="email"
                value={form.email}
                onChange={(e) => updateForm('email', e.target.value)}
                placeholder="your.email@example.com"
                required
                error={errors.email}
              />
              <FormInput
                label="Phone (Optional)"
                value={form.phone}
                onChange={(e) => updateForm('phone', e.target.value)}
                placeholder="+966 5X XXX XXXX"
              />
            </div>
          </div>

          {/* Team Selection */}
          {!teamParam && teams.length > 0 && (
            <div>
              <h2 className="text-sm font-semibold text-text-primary mb-2">Which team should handle your issue?</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="">Select a team</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">Issue Details</h2>

            <div className="space-y-3">
              <div>
                <label className="block text-sm font-medium text-text-primary mb-1.5">
                  Category <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  value={form.category}
                  onChange={(e) => updateForm('category', e.target.value)}
                  placeholder="e.g., Marketing, IT, Operations"
                  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">
                  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">
                  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="Title"
                value={form.title}
                onChange={(e) => updateForm('title', e.target.value)}
                placeholder="Brief summary of the issue"
                required
                error={errors.title}
              />

              <FormInput
                label="Description"
                type="textarea"
                value={form.description}
                onChange={(e) => updateForm('description', e.target.value)}
                placeholder="Provide detailed information about the issue..."
                rows={6}
                required
                error={errors.description}
              />
            </div>
          </div>

          {/* File Upload */}
          <div>
            <h2 className="text-sm font-semibold text-text-primary mb-2">Attachment (Optional)</h2>
            <label className="block cursor-pointer">
              <input type="file" onChange={handleFileChange} 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">Click to upload a file (screenshots, documents, etc.)</p>
                )}
              </div>
            </label>
          </div>

          {/* Submit Button */}
          <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"></div>
                Submitting...
              </>
            ) : (
              <>
                <Send className="w-5 h-5" />
                Submit Issue
              </>
            )}
          </button>
        </form>

        {/* Footer Note */}
        <p className="text-xs text-text-tertiary text-center mt-4">
          You'll receive a tracking link to monitor the progress of your issue.
        </p>
      </div>
    </div>
  )
}
