'use client'

import { useState } from 'react'
import {
  DSRRequest,
  DSRStatus,
  DSR_TYPE_INFO,
  DSR_STATUS_INFO,
  getDaysRemaining,
  isOverdue,
} from '@/lib/sdk/dsr/types'
import { updateSDKDSRStatus } from '@/lib/sdk/dsr/api'
import { DSRWorkflowStepperCompact } from '@/components/sdk/dsr'

export function DSRDetailPanel({
  request,
  onClose,
  onUpdated
}: {
  request: DSRRequest
  onClose: () => void
  onUpdated: () => void
}) {
  const [isUpdatingStatus, setIsUpdatingStatus] = useState(false)
  const [actionError, setActionError] = useState<string | null>(null)

  const typeInfo = DSR_TYPE_INFO[request.type]
  const statusInfo = DSR_STATUS_INFO[request.status]
  const daysRemaining = getDaysRemaining(request.deadline.currentDeadline)
  const overdue = isOverdue(request)

  type StatusTransition = { label: string; next: DSRStatus; variant?: 'danger' }
  const statusTransitions: Partial<Record<DSRStatus, StatusTransition[]>> = {
    intake: [{ label: 'Identitaet pruefen', next: 'identity_verification' }],
    identity_verification: [{ label: 'Bearbeitung starten', next: 'processing' }],
    processing: [
      { label: 'Anfrage abschliessen', next: 'completed' },
      { label: 'Ablehnen', next: 'rejected', variant: 'danger' }
    ]
  }

  const transitions = statusTransitions[request.status] || []

  const handleStatusChange = async (newStatus: DSRStatus) => {
    setIsUpdatingStatus(true)
    setActionError(null)
    try {
      await updateSDKDSRStatus(request.id, newStatus)
      onUpdated()
    } catch (err: unknown) {
      setActionError(err instanceof Error ? err.message : 'Unbekannter Fehler')
    } finally {
      setIsUpdatingStatus(false)
    }
  }

  const handleExportPDF = () => {
    window.open(`/api/sdk/v1/compliance/dsr/${request.id}/export`, '_blank')
  }

  return (
    <>
      {/* Backdrop */}
      <div
        className="fixed inset-0 z-40 bg-black/30"
        onClick={onClose}
      />

      {/* Drawer */}
      <div className="fixed right-0 top-0 bottom-0 z-50 w-[600px] bg-white shadow-2xl overflow-y-auto">
        {/* Header */}
        <div className="sticky top-0 bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between">
          <div>
            <p className="text-xs text-gray-500 font-mono">{request.referenceNumber}</p>
            <h2 className="text-lg font-semibold text-gray-900 mt-0.5">
              {typeInfo.article} {typeInfo.labelShort}
            </h2>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={handleExportPDF}
              className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
              </svg>
              PDF
            </button>
            <button
              onClick={onClose}
              className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
        </div>

        <div className="p-6 space-y-6">
          {actionError && (
            <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700">
              {actionError}
            </div>
          )}

          {/* Workflow Stepper */}
          <div>
            <h3 className="text-sm font-medium text-gray-700 mb-3">Bearbeitungsstand</h3>
            <DSRWorkflowStepperCompact currentStatus={request.status} />
          </div>

          {/* Requester Info */}
          <div>
            <h3 className="text-sm font-medium text-gray-700 mb-3">Antragsteller</h3>
            <div className="space-y-2">
              <div className="flex items-center gap-3">
                <div className="w-8 h-8 bg-purple-100 rounded-full flex items-center justify-center text-purple-600 font-medium text-sm">
                  {request.requester.name.charAt(0).toUpperCase()}
                </div>
                <div>
                  <p className="text-sm font-medium text-gray-900">{request.requester.name}</p>
                  <p className="text-xs text-gray-500">{request.requester.email}</p>
                </div>
              </div>
            </div>
          </div>

          {/* Deadline */}
          <div className={`p-4 rounded-lg border ${
            overdue ? 'bg-red-50 border-red-200' : 'bg-gray-50 border-gray-200'
          }`}>
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs text-gray-500">Gesetzliche Frist</p>
                <p className="text-sm font-medium text-gray-900">
                  {new Date(request.deadline.currentDeadline).toLocaleDateString('de-DE')}
                </p>
              </div>
              <div className={`text-right ${overdue ? 'text-red-600' : daysRemaining <= 7 ? 'text-orange-600' : 'text-gray-600'}`}>
                <p className="text-lg font-bold">
                  {overdue ? `${Math.abs(daysRemaining)}` : daysRemaining}
                </p>
                <p className="text-xs">
                  {overdue ? 'Tage ueberfaellig' : 'Tage verbleibend'}
                </p>
              </div>
            </div>
          </div>

          {/* Details */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <p className="text-xs text-gray-500">Status</p>
              <p className="text-sm font-medium text-gray-900">{statusInfo.label}</p>
            </div>
            <div>
              <p className="text-xs text-gray-500">Zugewiesen an</p>
              <p className="text-sm font-medium text-gray-900">
                {request.assignment?.assignedTo || '—'}
              </p>
            </div>
            <div>
              <p className="text-xs text-gray-500">Eingegangen am</p>
              <p className="text-sm font-medium text-gray-900">
                {new Date(request.receivedAt).toLocaleDateString('de-DE')}
              </p>
            </div>
            <div>
              <p className="text-xs text-gray-500">Identitaet geprueft</p>
              <p className={`text-sm font-medium ${request.identityVerification.verified ? 'text-green-600' : 'text-yellow-600'}`}>
                {request.identityVerification.verified ? 'Ja' : 'Ausstehend'}
              </p>
            </div>
          </div>

          {/* Notes */}
          {request.notes && (
            <div>
              <h3 className="text-sm font-medium text-gray-700 mb-2">Notizen</h3>
              <p className="text-sm text-gray-600 whitespace-pre-wrap">{request.notes}</p>
            </div>
          )}

          {/* Status Transitions */}
          {transitions.length > 0 && (
            <div>
              <h3 className="text-sm font-medium text-gray-700 mb-3">Naechste Schritte</h3>
              <div className="flex flex-wrap gap-2">
                {transitions.map((t) => (
                  <button
                    key={t.next}
                    onClick={() => handleStatusChange(t.next)}
                    disabled={isUpdatingStatus}
                    className={`px-4 py-2 text-sm rounded-lg disabled:opacity-50 disabled:cursor-not-allowed transition-colors ${
                      t.variant === 'danger'
                        ? 'bg-red-600 text-white hover:bg-red-700'
                        : 'bg-purple-600 text-white hover:bg-purple-700'
                    }`}
                  >
                    {isUpdatingStatus ? 'Wird gespeichert...' : t.label}
                  </button>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </>
  )
}
