// /opt/erp-system/app/tickets/[id]/page.tsx
'use client';

import { useState, useEffect, useRef } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { useSession } from "next-auth/react";
import { Send, CheckCircle, Clock, ArrowLeft, StickyNote, Activity, User as UserIcon, Paperclip, FileText, Download, AlertTriangle } from 'lucide-react';
import { useToast } from '../../components/ToastProvider';
import { getStatusBadge, getPriorityBadge } from '../../components/AppShell';

export default function TicketDetailPage() {
  const params = useParams();
  const router = useRouter();
  const { data: session } = useSession();
  const ticketId = params.id;
  const { toast } = useToast();

  const [ticket, setTicket] = useState<any>(null);
  const [users, setUsers] = useState<any[]>([]);
  const [attachments, setAttachments] = useState<any[]>([]);
  const [error, setError] = useState(false);
  const [messageInput, setMessageInput] = useState('');
  const [uploading, setUploading] = useState(false);
  
  const [showModal, setShowModal] = useState(false);
  const [modalMode, setModalMode] = useState<'addTime' | 'close' | 'addNote'>('addTime');
  const [modalData, setModalData] = useState({ durationMins: 15, description: '', content: '' });

  const fileInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (ticketId) {
      fetchTicket();
      fetchAttachments();
      if ((session?.user as any)?.userType === 'TEAM') {
        fetchUsers();
      }
    }
  }, [ticketId, session]);

  const fetchTicket = async () => {
    try {
      const res = await fetch(`/api/tickets/${ticketId}`);
      if (res.ok) setTicket(await res.json());
      else setError(true);
    } catch (err) {
      setError(true);
    }
  };

  const fetchUsers = async () => {
    const res = await fetch('/api/users');
    if (res.ok) setUsers(await res.json());
  };

  const fetchAttachments = async () => {
    const res = await fetch(`/api/tickets/${ticketId}/attachments`);
    if (res.ok) setAttachments(await res.json());
  };

  const handleSendMessage = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!messageInput.trim()) return;
    await fetch(`/api/tickets/${ticketId}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ action: 'addMessage', content: messageInput })
    });
    setMessageInput('');
    fetchTicket();
  };

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploading(true);
    const formData = new FormData();
    formData.append('file', file);

    const res = await fetch(`/api/tickets/${ticketId}/attachments`, {
      method: 'POST',
      body: formData
    });

    setUploading(false);
    if (fileInputRef.current) fileInputRef.current.value = '';

    if (res.ok) {
      fetchAttachments();
      fetchTicket();
    } else {
      toast('Fehler beim Hochladen der Datei.', 'error');
    }
  };

  const handleAssign = async (userId: string) => {
    await fetch(`/api/tickets/${ticketId}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ action: 'assign', userId })
    });
    fetchTicket();
  };

  const handleChangePriority = async (priority: string) => {
    await fetch(`/api/tickets/${ticketId}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ action: 'changePriority', priority })
    });
    fetchTicket();
  };

  const handleModalSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    let payload = {};

    if (modalMode === 'addNote') {
      payload = { action: 'addNote', content: modalData.content };
    } else {
      const action = modalMode === 'close' ? 'closeTicket' : 'addTimeEntry';
      payload = { action, durationMins: modalData.durationMins, description: modalData.description };
    }
    
    const res = await fetch(`/api/tickets/${ticketId}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    });

    if (res.ok) {
      setShowModal(false);
      setModalData({ durationMins: 15, description: '', content: '' });
      fetchTicket();
    }
  };

  const openModal = (mode: 'addTime' | 'close' | 'addNote') => {
    setModalMode(mode);
    setShowModal(true);
  };

  const formatBytes = (bytes: number) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  if (error) return <div className="p-8 text-red-600 font-medium">Fehler: Ticket konnte nicht geladen werden.</div>;
  if (!ticket) return <div className="p-8 text-slate-500 font-medium animate-pulse">Lade Ticketdaten...</div>;

  const isClosed = ticket.status === 'RESOLVED' || ticket.status === 'CLOSED';
  const userType = (session?.user as any)?.userType;

  const timelineItems = [
    ...(ticket.timeEntries || []).map((entry: any) => ({ ...entry, type: 'time' })),
    ...(ticket.notes || []).map((note: any) => ({ ...note, type: 'note' }))
  ].sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());

  return (
    <div className="max-w-7xl mx-auto space-y-6 relative pb-12 animate-fade-in-up">
      <div className="flex items-center gap-4">
        <button onClick={() => router.push('/')} className="p-2 hover:bg-slate-200 rounded-lg text-slate-600 transition">
          <ArrowLeft className="w-5 h-5" />
        </button>
        <div>
          <h1 className="text-2xl font-bold text-slate-900 mb-1">#{ticket.id}: {ticket.title}</h1>
          <div className="flex items-center gap-3 mt-2">
            {getStatusBadge(ticket.status)}
            {getPriorityBadge(ticket.priority)}
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2 space-y-4">
          <div className="bg-white p-6 rounded-2xl shadow-lg shadow-slate-200/50 border border-slate-100">
            <h3 className="font-semibold text-slate-800 mb-2">Beschreibung</h3>
            <p className="text-slate-600 whitespace-pre-wrap">{ticket.description}</p>
          </div>

          <div className="bg-white rounded-2xl shadow-lg shadow-slate-200/50 border border-slate-100 flex flex-col h-[500px]">
            <div className="p-4 border-b border-slate-200 font-semibold text-slate-800">Nachrichtenverlauf</div>
            <div className="flex-1 p-4 overflow-y-auto space-y-4 bg-slate-50">
              {ticket.messages.length === 0 ? (
                <p className="text-center text-slate-400 mt-4">Noch keine Nachrichten.</p>
              ) : (
                ticket.messages.map((msg: any) => (
                  <div key={msg.id} className={`flex ${msg.isFromCustomer ? 'justify-end' : 'justify-start'}`}>
                    <div className={`max-w-[75%] p-3 rounded-lg ${msg.isFromCustomer ? 'bg-indigo-600 text-white shadow-sm' : 'bg-white border border-slate-200 text-slate-800'}`}>
                      <p className="text-sm whitespace-pre-wrap">{msg.content}</p>
                      <span className={`text-[10px] mt-1 block ${msg.isFromCustomer ? 'text-indigo-200' : 'text-slate-400'}`}>
                        {new Date(msg.createdAt).toLocaleString('de-DE')}
                      </span>
                    </div>
                  </div>
                ))
              )}
            </div>

            {!isClosed && (
              <div className="p-4 border-t border-slate-200 bg-white">
                <form onSubmit={handleSendMessage} className="flex gap-2">
                  <input type="text" value={messageInput} onChange={(e) => setMessageInput(e.target.value)} placeholder="Antwort schreiben..." className="flex-1 border border-slate-300 p-2.5 rounded-xl focus-ring outline-none transition-all" />
                  <input type="file" className="hidden" ref={fileInputRef} onChange={handleFileUpload} />
                  <button type="button" onClick={() => fileInputRef.current?.click()} disabled={uploading} className="bg-slate-100 text-slate-600 p-2.5 rounded-lg hover:bg-slate-200 transition">
                    <Paperclip className="w-5 h-5" />
                  </button>
                  <button type="submit" className="bg-indigo-600 text-white p-2.5 rounded-lg hover:bg-indigo-700 transition">
                    <Send className="w-5 h-5" />
                  </button>
                </form>
              </div>
            )}
          </div>
        </div>

        <div className="space-y-6">
          <div className="bg-white p-6 rounded-2xl shadow-lg shadow-slate-200/50 border border-slate-100">
            <h3 className="font-semibold text-slate-800 mb-4 flex items-center gap-2">
              <Paperclip className="w-5 h-5 text-slate-500" /> Anhänge ({attachments.length})
            </h3>
            {attachments.length > 0 ? (
              <div className="space-y-2">
                {attachments.map(att => (
                  <div key={att.id} className="flex items-center justify-between p-2 hover:bg-slate-50 rounded-lg border border-slate-200 group">
                    <div className="flex items-center gap-2 overflow-hidden">
                      <FileText className="w-4 h-4 text-slate-400 flex-shrink-0" />
                      <div className="truncate">
                        <p className="text-sm font-medium text-slate-700 truncate">{att.fileName}</p>
                        <p className="text-[10px] text-slate-400">{formatBytes(att.fileSize)}</p>
                      </div>
                    </div>
                    <a href={`/api/tickets/${ticketId}/attachments?download=${att.id}`} download className="p-1.5 text-slate-500 hover:text-indigo-600 transition">
                      <Download className="w-4 h-4" />
                    </a>
                  </div>
                ))}
              </div>
            ) : (
              <p className="text-sm text-slate-500">Keine Dateien vorhanden.</p>
            )}
          </div>

          {userType === 'TEAM' && (
            <>
              <div className="bg-white p-6 rounded-2xl shadow-lg shadow-slate-200/50 border border-slate-100 space-y-4">
                <div>
                  <h3 className="font-semibold text-slate-800 mb-2 flex items-center gap-2">
                    <UserIcon className="w-4 h-4 text-slate-400" /> Bearbeiter
                  </h3>
                  <select className="w-full border border-slate-300 p-2 rounded-lg text-sm bg-white" value={ticket.assignedToId || ''} onChange={(e) => handleAssign(e.target.value)} disabled={isClosed}>
                    <option value="">Nicht zugewiesen</option>
                    {users.map(u => <option key={u.id} value={u.id}>{u.firstName} {u.lastName}</option>)}
                  </select>
                </div>
                <div>
                  <h3 className="font-semibold text-slate-800 mb-2 flex items-center gap-2">
                    <AlertTriangle className="w-4 h-4 text-slate-400" /> Priorität
                  </h3>
                  <select className="w-full border border-slate-300 p-2 rounded-lg text-sm bg-white" value={ticket.priority} onChange={(e) => handleChangePriority(e.target.value)} disabled={isClosed}>
                    <option value="LOW">Niedrig</option>
                    <option value="MEDIUM">Mittel</option>
                    <option value="HIGH">Hoch</option>
                    <option value="CRITICAL">Kritisch</option>
                  </select>
                </div>
              </div>

              {!isClosed && (
                <div className="bg-white p-6 rounded-2xl shadow-lg shadow-slate-200/50 border border-slate-100">
                  <h3 className="font-semibold text-slate-800 mb-4">Aktionen</h3>
                  <div className="space-y-3">
                    <div className="grid grid-cols-2 gap-3">
                      <button onClick={() => openModal('addTime')} className="bg-indigo-50 text-indigo-700 border border-indigo-200 px-4 py-2.5 rounded-lg text-sm font-medium"><Clock className="w-4 h-4" /> Zeit buchen</button>
                      <button onClick={() => openModal('addNote')} className="bg-slate-50 text-slate-700 border border-slate-200 px-4 py-2.5 rounded-lg text-sm font-medium"><StickyNote className="w-4 h-4" /> Int. Notiz</button>
                    </div>
                    <button onClick={() => openModal('close')} className="w-full bg-emerald-600 text-white px-4 py-2.5 rounded-lg text-sm font-medium shadow-sm"><CheckCircle className="w-4 h-4" /> Ticket abschließen</button>
                  </div>
                </div>
              )}

              <div className="bg-white p-6 rounded-2xl shadow-lg shadow-slate-200/50 border border-slate-100">
                <h3 className="font-semibold text-slate-800 mb-4 flex items-center gap-2"><Activity className="w-5 h-5 text-slate-500" /> Interne Chronik</h3>
                <div className="space-y-6">
                  {timelineItems.map((item: any) => (
                    <div key={`${item.type}-${item.id}`} className={`border-l-2 pl-4 relative ${item.type === 'time' ? 'border-amber-400' : 'border-indigo-400'}`}>
                      <p className="font-semibold text-slate-800 text-sm">{item.type === 'time' ? `Zeit: ${item.durationMins} Min.` : 'Interne Notiz'}</p>
                      <p className="text-sm text-slate-600 mt-1">{item.type === 'time' ? item.description : item.content}</p>
                      <div className="text-[10px] text-slate-400 mt-1">{new Date(item.createdAt).toLocaleString('de-DE')} • {item.user?.firstName}</div>
                    </div>
                  ))}
                </div>
              </div>
            </>
          )}
        </div>
      </div>

      {showModal && (
        <div className="fixed inset-0 bg-slate-900/60 flex items-center justify-center z-50 backdrop-blur-sm p-4">
          <div className="bg-white p-8 rounded-2xl shadow-xl max-w-md w-full">
            <h2 className="text-xl font-bold text-slate-900 mb-2">{modalMode === 'addNote' ? 'Interne Notiz' : 'Zeit erfassen'}</h2>
            <form onSubmit={handleModalSubmit} className="space-y-4 mt-6">
              {modalMode !== 'addNote' && (
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">Dauer (Min.) *</label>
                  <input type="number" step="15" required value={modalData.durationMins} onChange={(e) => setModalData({...modalData, durationMins: parseInt(e.target.value)})} className="w-full border border-slate-300 p-2.5 rounded-xl focus-ring outline-none transition-all" />
                </div>
              )}
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Inhalt *</label>
                {/* HIER WAR DER FEHLER: setModalData statt setFormData */}
                <textarea required value={modalMode === 'addNote' ? modalData.content : modalData.description} onChange={(e) => setModalData(modalMode === 'addNote' ? {...modalData, content: e.target.value} : {...modalData, description: e.target.value})} className="w-full border border-slate-300 p-2.5 rounded-xl focus-ring outline-none h-24 resize-none transition-all" />
              </div>
              <div className="flex justify-end gap-3 mt-6">
                <button type="button" onClick={() => setShowModal(false)} className="px-4 py-2.5 text-slate-600">Abbrechen</button>
                <button type="submit" className="bg-indigo-600 text-white px-6 py-2.5 rounded-lg">Speichern</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
