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

const STATUS_CONFIG = {
  new: { label: 'New', bg: 'bg-purple-100', text: 'text-purple-700', dot: 'bg-purple-500', icon: AlertCircle },
  acknowledged: { label: 'Acknowledged', bg: 'bg-blue-100', text: 'text-blue-700', dot: 'bg-blue-500', icon: CheckCircle2 },
  in_progress: { label: 'In Progress', bg: 'bg-amber-100', text: 'text-amber-700', dot: 'bg-amber-500', icon: Clock },
  resolved: { label: 'Resolved', bg: 'bg-emerald-100', text: 'text-emerald-700', dot: 'bg-emerald-500', icon: CheckCircle2 },
  declined: { label: 'Declined', bg: 'bg-gray-100', text: 'text-gray-700', dot: 'bg-gray-500', icon: XCircle },
}

const PRIORITY_CONFIG = {
  low: { label: 'Low', color: 'text-gray-700' },
  medium: { label: 'Medium', color: 'text-blue-700' },
  high: { label: 'High', color: 'text-orange-700' },
  urgent: { label: 'Urgent', color: 'text-red-700' },
}

export default function PublicIssueTracker() {
  const { token } = useParams()
  const toast = useToast()
  const [issue, setIssue] = useState(null)
  const [updates, setUpdates] = useState([])
  const [attachments, setAttachments] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)

  // Comment form
  const [commentName, setCommentName] = useState('')
  const [commentMessage, setCommentMessage] = useState('')
  const [submittingComment, setSubmittingComment] = useState(false)

  // File upload
  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) {
      console.error('Failed to load issue:', err)
      setError(err.response?.status === 404 ? 'Issue not found' : 'Failed to load issue')
    } 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 (err) {
      console.error('Failed to add comment:', err)
      toast.error('Failed to add comment')
    } 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 = '' // Reset input
    } catch (err) {
      console.error('Failed to upload file:', err)
      toast.error('Failed to upload file')
    } finally {
      setUploadingFile(false)
    }
  }

  const formatDate = (dateStr) => {
    if (!dateStr) return ''
    const date = new Date(dateStr)
    return date.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' })
  }

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

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

  if (loading) {
    return (
      <div className="min-h-screen bg-surface-secondary py-8 px-4">
        <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>
            <div className="h-7 bg-surface-tertiary rounded w-3/4"></div>
            <div className="h-4 bg-surface-tertiary rounded w-full"></div>
            <div className="h-4 bg-surface-tertiary rounded w-2/3"></div>
          </div>
          <div className="bg-surface rounded-xl border border-border p-6 space-y-4">
            <div className="h-5 bg-surface-tertiary rounded w-40"></div>
            <div className="h-20 bg-surface-tertiary rounded"></div>
          </div>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="min-h-screen bg-surface-secondary py-8 px-4 ">
        <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">Issue Not Found</h1>
          <p className="text-sm text-text-tertiary mb-6">
            The tracking link you used is invalid or the issue has been removed.
          </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"
          >
            Submit a New Issue
          </a>
        </div>
      </div>
    )
  }

  if (!issue) return null

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

  return (
    <div className="min-h-screen bg-surface-secondary py-8 px-4 ">
      <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}`}></span>
                {statusConfig.label}
              </span>
              <span className={`text-xs font-medium ${priorityConfig.color}`}>
                {priorityConfig.label} 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">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">Submitted:</span>
              <span className="text-text-primary font-medium ml-2">{formatDate(issue.created_at)}</span>
            </div>
            <div>
              <span className="text-text-tertiary">Last Updated:</span>
              <span className="text-text-primary font-medium ml-2">{formatDate(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' ? 'Resolution' : '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'}`}>
                    {formatDate(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" />
            Progress Updates
          </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">No updates yet. We'll post updates here as we work on your issue.</p>
            </div>
          ) : (
            <div className="space-y-4">
              {updates.map((update, idx) => (
                <div key={update.Id || update.id || idx} className="border-l-4 border-brand-primary pl-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' ? 'Team' : 'You'}
                      </span>
                    </div>
                    <span className="text-sm text-text-tertiary">{formatDateTime(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" />
              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">
                        {formatFileSize(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 ml-2"
                  >
                    Download
                  </a>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Add Comment Section */}
        {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" />
              Add a Comment
            </h2>

            <form onSubmit={handleAddComment} className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-text-primary mb-2">Your Name (Optional)</label>
                <input
                  type="text"
                  value={commentName}
                  onChange={(e) => setCommentName(e.target.value)}
                  placeholder="Your name"
                  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">
                  Message <span className="text-red-500">*</span>
                </label>
                <textarea
                  value={commentMessage}
                  onChange={(e) => setCommentMessage(e.target.value)}
                  placeholder="Add additional information or ask a question..."
                  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 ? 'Sending...' : 'Send Comment'}
                </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 ? 'Uploading...' : 'Upload File'}
                  </div>
                </label>
              </div>
            </form>
          </div>
        )}

        {/* Footer */}
        <div className="text-center mt-8">
          <p className="text-sm text-text-tertiary">
            Bookmark this page to check your issue status anytime.
          </p>
        </div>
      </div>
    </div>
  )
}
