import { useState } from 'react'
import { FaLock, FaLockOpen, FaPlay, FaStop, FaTruck, FaSackDollar, FaUserGear, FaPlus, FaClockRotateLeft, FaPen } from 'react-icons/fa6'
import { formatDistanceToNow, format } from 'date-fns'
import { de } from 'date-fns/locale'
import StatusDropdown from './StatusDropdown'
import PriorityDropdown from './PriorityDropdown'
import EditorDropdown from './EditorDropdown'
import ResponseDropdown from './ResponseDropdown'
import CreateWorksheetModal from './CreateWorksheetModal'
import EditWorksheetTimeModal from './EditWorksheetTimeModal'
import StatusHistoryModal from './StatusHistoryModal'
import WorksheetList from './WorksheetList'
import WorksheetStats from './WorksheetStats'
import TicketAssignedProjectsPanel from './TicketAssignedProjectsPanel'
import TicketProjectsModal from './TicketProjectsModal'
import InvoicePanel from './InvoicePanel'
import DocumentsPanel from './DocumentsPanel'
import { useWorksheets } from '../hooks/useWorksheets'

const PRIORITY_CLASSES = {
  0: 'priority-none',
  1: 'priority-low',
  2: 'priority-medium',
  3: 'priority-high',
  4: 'priority-critical'
}

const STATUS_CLASSES = {
  'Open': 'status-open',
  'Occupied': 'status-occupied',
  'Assigned': 'status-assigned',
  'Awaiting': 'status-awaiting',
  'Closed': 'status-closed'
}

const APPROVAL_ICONS = {
  'pending': FaUserGear,
  'approved': FaSackDollar,
  'quote': FaSackDollar,
  'shipping': FaTruck
}

const TABS = [
  { id: 'details', label: 'Details' },
  { id: 'worksheets', label: 'Arbeitsblaetter' },
  { id: 'invoices', label: 'Rechnungen' },
  { id: 'documents', label: 'Dokumente' },
  { id: 'project', label: 'Projekt / Preview' },
]

export default function TicketRow({ ticket, onUpdate, onExpand }) {
  const [expanded, setExpanded] = useState(false)
  const [locked, setLocked] = useState(true)
  const [activeTab, setActiveTab] = useState('details')
  const [showCreateWorksheet, setShowCreateWorksheet] = useState(false)
  const [editTimeWorksheet, setEditTimeWorksheet] = useState(null)
  const [showHistoryModal, setShowHistoryModal] = useState(false)
  const [showProjectsModal, setShowProjectsModal] = useState(false)
  const [projectsRefreshKey, setProjectsRefreshKey] = useState(0)

  const {
    worksheets,
    loading: worksheetsLoading,
    createWorksheet,
    updateWorksheet,
    getTotalTime
  } = useWorksheets(expanded ? ticket.woid : null)

  // Startzeit fuer Git-Push-Worksheets nachtragen (Endzeit kam vom Push)
  const handleSaveWorksheetTime = async (ws, data) => updateWorksheet(ws.$id, data)

  const createdAt = new Date(ticket.$createdAt || ticket.createdAt)
  const elapsed = formatDistanceToNow(createdAt, { locale: de })

  const handleStatusChange = (newStatus) => onUpdate(ticket.$id, { status: newStatus })
  const handlePriorityChange = (newPriority) => onUpdate(ticket.$id, { priority: newPriority })
  const handleEditorChange = (newEditor) => onUpdate(ticket.$id, { assignedTo: newEditor })
  const handleResponseChange = (newResponse) => onUpdate(ticket.$id, { responseLevel: newResponse })

  const toggleLock = () => {
    if (locked) {
      setExpanded(true)
      onExpand?.(ticket.$id)
    } else {
      setExpanded(false)
    }
    setLocked(!locked)
  }

  const handleCreateWorksheet = async (worksheetData, currentUser) => {
    const result = await createWorksheet(worksheetData, currentUser)
    if (result.success && worksheetData.newStatus !== ticket.status) {
      await onUpdate(ticket.$id, {
        status: worksheetData.newStatus,
        responseLevel: worksheetData.newResponseLevel || ticket.responseLevel
      })
    }
    return result
  }

  const ApprovalIcon = APPROVAL_ICONS[ticket.approvalStatus] || FaUserGear

  return (
    <>
      <tr className={`ticket-row ${expanded ? 'ticket-expanded' : 'ticket-collapsed'}`}>
        <td className={`ticket-id ${expanded ? 'ticket-id-expanded' : ''}`} rowSpan={2}>
          <div><strong>WOID:</strong> {ticket.woid || ticket.$id?.slice(-5)}</div>
          <div className="ticket-time">{elapsed}</div>
        </td>
        <td className="ticket-info" rowSpan={2}>
          <strong>{format(createdAt, 'dd.MM.yyyy')}</strong>
        </td>
        <td className="ticket-info" rowSpan={2}>
          <strong>{ticket.type}</strong>
          <br />
          {ticket.serviceType || 'Remote'}
          <br />
          <FaPlay className="text-green" /> {ticket.startDate || format(createdAt, 'dd.MM.yyyy')}
          <br />
          <FaStop className="text-red" /> {ticket.deadline || '-'}
        </td>
        <td className="ticket-info" rowSpan={2}>
          <strong>{ticket.systemType || 'n/a'}</strong>
        </td>
        <td rowSpan={2}>
          <strong>{ticket.customerName || 'Unknown'}</strong>
          <br />
          {ticket.customerLocation || ''}
        </td>
        <td rowSpan={2}>
          <strong>{ticket.requestedBy || '-'}</strong>
          <br />
          {ticket.requestedFor && <>Requested for: {ticket.requestedFor}<br /></>}
          {ticket.topic}
        </td>
        <td className={`text-center ${STATUS_CLASSES[ticket.status] || 'status-open'}`}>
          <StatusDropdown value={ticket.status} onChange={handleStatusChange} />
        </td>
        <td className={`text-center ${PRIORITY_CLASSES[ticket.priority] || 'priority-low'}`}>
          <PriorityDropdown value={ticket.priority} onChange={handlePriorityChange} />
        </td>
        <td
          className={`text-center ${ticket.approvalStatus === 'approved' ? 'bg-green' : 'bg-yellow'}`}
          rowSpan={2}
          style={{ verticalAlign: 'middle' }}
        >
          <ApprovalIcon size={24} />
        </td>
        <td
          className="bg-dark-grey text-center text-white"
          rowSpan={2}
          style={{ verticalAlign: 'middle', cursor: 'pointer' }}
          onClick={toggleLock}
        >
          {locked ? <FaLock size={24} /> : <FaLockOpen size={24} />}
        </td>
      </tr>
      <tr className="ticket-row">
        <td className={`text-center ${STATUS_CLASSES[ticket.status] || 'status-open'}`}>
          <EditorDropdown value={ticket.assignedTo} onChange={handleEditorChange} />
        </td>
        <td className={`text-center ${PRIORITY_CLASSES[ticket.priority] || 'priority-low'}`}>
          <ResponseDropdown value={ticket.responseLevel} onChange={handleResponseChange} />
        </td>
      </tr>
      {expanded && (
        <tr className="worksheet-expansion">
          <td colSpan={10} className="worksheet-cell">
            <div className="card" style={{
              borderRadius: '0 0 12px 12px',
              marginTop: 0,
              border: '1px solid rgba(16, 185, 129, 0.2)',
              borderTop: 'none'
            }}>
              <div className="card-body" style={{ borderRadius: '0 0 12px 12px', padding: '20px' }}>

                {/* Tab-Leiste */}
                <div className="ticket-tabs">
                  {TABS.map((t) => (
                    <button
                      key={t.id}
                      type="button"
                      className={`ticket-tab ${activeTab === t.id ? 'ticket-tab-active' : ''}`}
                      onClick={() => setActiveTab(t.id)}
                    >
                      {t.label}
                    </button>
                  ))}
                </div>

                <div className="ticket-tab-content">
                  {activeTab === 'details' && (
                    <div style={{
                      background: 'rgba(45, 55, 72, 0.5)',
                      borderRadius: '12px',
                      padding: '20px',
                      border: '1px solid rgba(16, 185, 129, 0.2)',
                    }}>
                      <h5 style={{ color: 'var(--dark-text)', fontWeight: 'bold', marginBottom: '16px', fontSize: '18px' }}>
                        Ticket-Beschreibung
                      </h5>
                      <p style={{ fontSize: '14px', lineHeight: '1.8', color: 'rgba(226, 232, 240, 0.85)', whiteSpace: 'pre-wrap', margin: 0 }}>
                        {ticket.details || 'Keine Details vorhanden.'}
                      </p>
                    </div>
                  )}

                  {activeTab === 'worksheets' && (
                    <div>
                      <div style={{ display: 'flex', gap: '8px', alignItems: 'stretch', marginBottom: '16px' }}>
                        <button
                          className="btn"
                          style={{
                            background: 'linear-gradient(135deg, #10b981 0%, #059669 100%)',
                            color: 'white', border: 'none', padding: '12px 20px', borderRadius: '8px',
                            fontWeight: 'bold', cursor: 'pointer', flex: 1
                          }}
                          onClick={() => setShowCreateWorksheet(true)}
                        >
                          <FaPlus style={{ marginRight: '8px' }} /> Add Worksheet
                        </button>
                        <button
                          type="button"
                          style={{ background: '#3b82f6', color: 'white', border: 'none', padding: '12px', borderRadius: '8px', cursor: 'pointer', minWidth: '44px' }}
                          onClick={() => setShowProjectsModal(true)}
                          title="Projekte bearbeiten"
                        >
                          <FaPen size={18} />
                        </button>
                        <button
                          type="button"
                          style={{ background: '#616161', color: 'white', border: 'none', padding: '12px', borderRadius: '8px', cursor: 'pointer', minWidth: '44px' }}
                          onClick={() => setShowHistoryModal(true)}
                          title="Status History"
                        >
                          <FaClockRotateLeft size={18} />
                        </button>
                      </div>

                      {worksheets.length > 0 && (
                        <div style={{ background: 'rgba(45, 55, 72, 0.5)', borderRadius: '12px', padding: '16px', border: '1px solid rgba(16, 185, 129, 0.2)', marginBottom: '16px' }}>
                          <WorksheetStats worksheets={worksheets} />
                        </div>
                      )}

                      <WorksheetList worksheets={worksheets} totalTime={getTotalTime()} loading={worksheetsLoading} onEditTime={setEditTimeWorksheet} />
                    </div>
                  )}

                  {activeTab === 'invoices' && <InvoicePanel ticket={ticket} />}

                  {activeTab === 'documents' && <DocumentsPanel ticket={ticket} />}

                  {activeTab === 'project' && (
                    <div>
                      <button
                        type="button"
                        className="btn btn-green"
                        style={{ marginBottom: '12px' }}
                        onClick={() => setShowProjectsModal(true)}
                      >
                        <FaPen style={{ marginRight: 6 }} /> Projekte zuweisen / bearbeiten
                      </button>
                      <TicketAssignedProjectsPanel ticket={ticket} refreshKey={projectsRefreshKey} />
                    </div>
                  )}
                </div>
              </div>
            </div>
          </td>
        </tr>
      )}

      <CreateWorksheetModal
        isOpen={showCreateWorksheet}
        onClose={() => setShowCreateWorksheet(false)}
        workorder={ticket}
        onCreate={handleCreateWorksheet}
      />

      <EditWorksheetTimeModal
        isOpen={Boolean(editTimeWorksheet)}
        onClose={() => setEditTimeWorksheet(null)}
        worksheet={editTimeWorksheet}
        onSave={handleSaveWorksheetTime}
      />

      <StatusHistoryModal
        isOpen={showHistoryModal}
        onClose={() => setShowHistoryModal(false)}
        worksheets={worksheets}
        ticket={ticket}
      />

      <TicketProjectsModal
        isOpen={showProjectsModal}
        onClose={() => setShowProjectsModal(false)}
        ticket={ticket}
        onUpdated={() => setProjectsRefreshKey((k) => k + 1)}
      />
      <tr className="spacer">
        <td colSpan={10} style={{ height: '12px', background: 'transparent', border: 'none' }}></td>
      </tr>
    </>
  )
}
