'use client';

import { useEffect, useState, useRef } from 'react';
import { useParams, useRouter } from 'next/navigation';

const ADMIN_API_URL = process.env.NEXT_PUBLIC_ADMIN_API_URL || 'http://localhost:3004/api';

interface Attachment {
  id: string;
  fileName: string;
  originalName: string;
  mimeType: string;
  sizeBytes: number;
  createdAt: string;
}

interface Comment {
  id: string;
  authorName: string;
  authorType: string;
  content: string;
  createdAt: string;
  attachments: Attachment[];
}

interface Ticket {
  id: string;
  subject: string;
  description: string;
  category: string;
  priority: string;
  status: string;
  createdByName: string;
  assignee: { firstName: string; lastName: string } | null;
  comments: Comment[];
  attachments: Attachment[];
  createdAt: string;
}

const statusColors: Record<string, string> = {
  open: 'bg-yellow-50 text-yellow-700',
  in_progress: 'bg-blue-50 text-blue-700',
  waiting_tenant: 'bg-orange-50 text-orange-700',
  resolved: 'bg-green-50 text-green-700',
  closed: 'bg-surface-100 text-surface-500',
};

function formatBytes(bytes: number) {
  if (bytes < 1024) return bytes + ' B';
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
  return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
}

export default function TicketDetailPage() {
  const params = useParams();
  const router = useRouter();
  const ticketId = params.id as string;

  const [ticket, setTicket] = useState<Ticket | null>(null);
  const [loading, setLoading] = useState(true);
  const [comment, setComment] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [uploading, setUploading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [selectedFiles, setSelectedFiles] = useState<File[]>([]);

  useEffect(() => {
    loadTicket();
  }, [ticketId]);

  function authHeaders() {
    const token = localStorage.getItem('accessToken');
    return { Authorization: `Bearer ${token}` };
  }

  async function loadTicket() {
    try {
      const res = await fetch(`${ADMIN_API_URL}/public/support/tickets/${ticketId}`, {
        headers: authHeaders(),
      });
      const data = await res.json();
      setTicket(data.data || data);
    } catch {
      // not found
    } finally {
      setLoading(false);
    }
  }

  async function handleAddComment() {
    if (!comment.trim() && selectedFiles.length === 0) return;
    setSubmitting(true);
    try {
      // Add comment first
      if (comment.trim()) {
        await fetch(`${ADMIN_API_URL}/public/support/tickets/${ticketId}/comments`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', ...authHeaders() },
          body: JSON.stringify({ content: comment }),
        });
      }

      // Upload files if any
      if (selectedFiles.length > 0) {
        const formData = new FormData();
        selectedFiles.forEach((f) => formData.append('files', f));
        await fetch(`${ADMIN_API_URL}/public/support/tickets/${ticketId}/attachments`, {
          method: 'POST',
          headers: authHeaders(),
          body: formData,
        });
      }

      setComment('');
      setSelectedFiles([]);
      loadTicket();
    } catch (err) {
      console.error('Failed to submit:', err);
    } finally {
      setSubmitting(false);
    }
  }

  async function handleFileUpload(files: FileList) {
    setUploading(true);
    try {
      const formData = new FormData();
      Array.from(files).forEach((f) => formData.append('files', f));
      await fetch(`${ADMIN_API_URL}/public/support/tickets/${ticketId}/attachments`, {
        method: 'POST',
        headers: authHeaders(),
        body: formData,
      });
      loadTicket();
    } catch (err) {
      console.error('Failed to upload:', err);
    } finally {
      setUploading(false);
    }
  }

  function handleDownload(fileName: string, originalName: string) {
    const token = localStorage.getItem('accessToken');
    window.open(`${ADMIN_API_URL}/public/support/uploads/${fileName}?token=${token}`, '_blank');
  }

  if (loading) return <div className="p-8 text-center text-surface-400">Loading...</div>;
  if (!ticket) return <div className="p-8 text-center text-surface-400">Ticket not found</div>;

  return (
    <div className="space-y-6">
      <button
        onClick={() => router.push('/dashboard/support')}
        className="text-sm text-surface-500 dark:text-surface-400 hover:text-surface-700 dark:hover:text-surface-300"
      >
        &larr; Back to support tickets
      </button>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Main content */}
        <div className="lg:col-span-2 space-y-6">
          {/* Ticket header */}
          <div className="bg-white dark:bg-surface-800 rounded-xl border border-surface-200 dark:border-surface-700 p-6">
            <div className="flex items-start justify-between mb-2">
              <h1 className="text-xl font-semibold text-surface-900 dark:text-surface-100">{ticket.subject}</h1>
              <span className={`inline-block px-2.5 py-1 rounded-full text-xs font-medium ${statusColors[ticket.status] || ''}`}>
                {ticket.status.replace(/_/g, ' ')}
              </span>
            </div>
            <p className="text-surface-600 dark:text-surface-300 whitespace-pre-wrap">{ticket.description}</p>
            <div className="mt-4 text-xs text-surface-400">
              Created {new Date(ticket.createdAt).toLocaleString()} by {ticket.createdByName}
            </div>
          </div>

          {/* Ticket-level attachments */}
          {ticket.attachments.length > 0 && (
            <div className="bg-white dark:bg-surface-800 rounded-xl border border-surface-200 dark:border-surface-700 p-4">
              <h3 className="text-sm font-medium text-surface-700 dark:text-surface-300 mb-3">Attachments</h3>
              <div className="flex flex-wrap gap-2">
                {ticket.attachments.map((a) => (
                  <button
                    key={a.id}
                    onClick={() => handleDownload(a.fileName, a.originalName)}
                    className="flex items-center gap-2 px-3 py-2 bg-surface-50 dark:bg-surface-700 border border-surface-200 dark:border-surface-600 rounded-lg text-sm hover:bg-surface-100 dark:hover:bg-surface-600 transition-colors"
                  >
                    {a.mimeType.startsWith('image/') ? (
                      <svg className="w-4 h-4 text-surface-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" /></svg>
                    ) : (
                      <svg className="w-4 h-4 text-surface-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15.172 7l-4.586 4.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" /></svg>
                    )}
                    <span className="text-surface-700 dark:text-surface-300">{a.originalName}</span>
                    <span className="text-surface-400">({formatBytes(a.sizeBytes)})</span>
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Comments thread */}
          <div className="space-y-4">
            <h3 className="text-sm font-medium text-surface-700 dark:text-surface-300">
              Conversation ({ticket.comments.length})
            </h3>
            {ticket.comments.map((c) => (
              <div
                key={c.id}
                className={`bg-white dark:bg-surface-800 rounded-lg border p-4 ${
                  c.authorType === 'super_admin' ? 'border-primary-200 bg-primary-50/30 dark:border-primary-700 dark:bg-primary-900/20' : 'border-surface-200 dark:border-surface-700'
                }`}
              >
                <div className="flex items-center justify-between mb-2">
                  <div className="flex items-center gap-2">
                    <span className="text-sm font-medium text-surface-700 dark:text-surface-300">{c.authorName}</span>
                    <span className={`text-xs px-1.5 py-0.5 rounded ${
                      c.authorType === 'super_admin' ? 'bg-primary-100 text-primary-700' : 'bg-surface-100 dark:bg-surface-700 text-surface-600 dark:text-surface-400'
                    }`}>
                      {c.authorType === 'super_admin' ? 'FiberOps Team' : 'You'}
                    </span>
                  </div>
                  <span className="text-xs text-surface-400">{new Date(c.createdAt).toLocaleString()}</span>
                </div>
                <p className="text-sm text-surface-700 dark:text-surface-300 whitespace-pre-wrap">{c.content}</p>

                {/* Comment attachments */}
                {c.attachments.length > 0 && (
                  <div className="flex flex-wrap gap-2 mt-3 pt-3 border-t border-surface-100 dark:border-surface-700">
                    {c.attachments.map((a) => (
                      <button
                        key={a.id}
                        onClick={() => handleDownload(a.fileName, a.originalName)}
                        className="flex items-center gap-1.5 px-2 py-1 bg-surface-50 dark:bg-surface-700 border border-surface-200 dark:border-surface-600 rounded text-xs hover:bg-surface-100 dark:hover:bg-surface-600"
                      >
                        <svg className="w-3 h-3 text-surface-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15.172 7l-4.586 4.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" /></svg>
                        {a.originalName} ({formatBytes(a.sizeBytes)})
                      </button>
                    ))}
                  </div>
                )}
              </div>
            ))}

            {/* Add comment form */}
            <div className="bg-white dark:bg-surface-800 rounded-xl border border-surface-200 dark:border-surface-700 p-4 space-y-3">
              <textarea
                value={comment}
                onChange={(e) => setComment(e.target.value)}
                rows={3}
                placeholder="Type your message..."
                className="w-full border border-surface-300 dark:border-surface-600 rounded-lg px-3 py-2 text-sm resize-none focus:outline-none focus:ring-2 focus:ring-primary-500 bg-white dark:bg-surface-700 text-surface-900 dark:text-surface-100"
              />

              {/* File selection preview */}
              {selectedFiles.length > 0 && (
                <div className="flex flex-wrap gap-2">
                  {selectedFiles.map((f, i) => (
                    <div key={i} className="flex items-center gap-1 px-2 py-1 bg-surface-50 dark:bg-surface-700 border border-surface-200 dark:border-surface-600 rounded text-xs">
                      <span className="text-surface-700 dark:text-surface-300">{f.name}</span>
                      <span className="text-surface-400">({formatBytes(f.size)})</span>
                      <button
                        onClick={() => setSelectedFiles(selectedFiles.filter((_, j) => j !== i))}
                        className="text-surface-400 hover:text-red-500 ml-1"
                      >
                        &times;
                      </button>
                    </div>
                  ))}
                </div>
              )}

              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <input
                    ref={fileInputRef}
                    type="file"
                    multiple
                    accept="image/*,.pdf,.txt,.doc,.docx"
                    className="hidden"
                    onChange={(e) => {
                      if (e.target.files) {
                        setSelectedFiles([...selectedFiles, ...Array.from(e.target.files!)]);
                        e.target.value = '';
                      }
                    }}
                  />
                  <button
                    onClick={() => fileInputRef.current?.click()}
                    className="px-3 py-1.5 text-sm text-surface-600 dark:text-surface-300 border border-surface-300 dark:border-surface-600 rounded-lg hover:bg-surface-50 dark:hover:bg-surface-700"
                  >
                    Attach files
                  </button>
                  <span className="text-xs text-surface-400">Max 5 files, 10MB each</span>
                </div>
                <button
                  onClick={handleAddComment}
                  disabled={submitting || (!comment.trim() && selectedFiles.length === 0)}
                  className="px-4 py-2 bg-primary-600 text-white rounded-lg text-sm hover:bg-primary-700 disabled:opacity-50"
                >
                  {submitting ? 'Sending...' : 'Send'}
                </button>
              </div>
            </div>
          </div>
        </div>

        {/* Sidebar */}
        <div className="space-y-4">
          <div className="bg-white dark:bg-surface-800 rounded-xl border border-surface-200 dark:border-surface-700 p-4 space-y-4">
            <h3 className="text-sm font-medium text-surface-700 dark:text-surface-300">Ticket Info</h3>

            <div>
              <label className="text-xs text-surface-500 dark:text-surface-400">Category</label>
              <p className="text-sm font-medium mt-1 capitalize text-surface-800 dark:text-surface-200">{ticket.category.replace(/_/g, ' ')}</p>
            </div>

            <div>
              <label className="text-xs text-surface-500 dark:text-surface-400">Priority</label>
              <p className={`text-sm font-medium mt-1 capitalize ${
                ticket.priority === 'urgent' ? 'text-red-600' :
                ticket.priority === 'high' ? 'text-orange-600' :
                ticket.priority === 'normal' ? 'text-surface-700 dark:text-surface-300' : 'text-surface-500 dark:text-surface-400'
              }`}>{ticket.priority}</p>
            </div>

            {ticket.assignee && (
              <div>
                <label className="text-xs text-surface-500 dark:text-surface-400">Assigned To</label>
                <p className="text-sm font-medium mt-1 text-surface-800 dark:text-surface-200">{ticket.assignee.firstName} {ticket.assignee.lastName}</p>
              </div>
            )}
          </div>

          {/* Upload files directly to ticket */}
          <div className="bg-white dark:bg-surface-800 rounded-xl border border-surface-200 dark:border-surface-700 p-4 space-y-3">
            <h3 className="text-sm font-medium text-surface-700 dark:text-surface-300">Upload Files</h3>
            <p className="text-xs text-surface-500 dark:text-surface-400">Attach screenshots, documents, or other files to this ticket.</p>
            <input
              type="file"
              multiple
              accept="image/*,.pdf,.txt,.doc,.docx"
              onChange={(e) => {
                if (e.target.files && e.target.files.length > 0) {
                  handleFileUpload(e.target.files);
                  e.target.value = '';
                }
              }}
              className="block w-full text-sm text-surface-500 file:mr-2 file:py-1.5 file:px-3 file:rounded-lg file:border-0 file:text-sm file:font-medium file:bg-primary-50 file:text-primary-700 hover:file:bg-primary-100"
            />
            {uploading && <p className="text-xs text-surface-400">Uploading...</p>}
          </div>
        </div>
      </div>
    </div>
  );
}
