import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Plus, Pencil, Trash2, PenLine, Search } from 'lucide-react'
import toast from 'react-hot-toast'
import { Button } from '@/components/ui/Button'
import { Input } from '@/components/ui/Input'
import { Label } from '@/components/ui/Label'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/Dialog'
import { RichTextEditor } from '@/components/RichTextEditor/RichTextEditor'
import {
  signaturesApi,
  type SignatureResponse,
  type SignatureCreate,
  type SignatureContext,
} from '@/api/signatures.api'
import { mailboxesApi } from '@/api/mailboxes.api'
import { virtualBoxesApi } from '@/api/virtual_boxes.api'
import { getErrorMessage } from '@/api/client'
import { formatDate } from '@/lib/utils'
import { useAuth } from '@/hooks/useAuth'

// ─── Tipi locali ──────────────────────────────────────────────────────────────

type Tab = 'library' | 'mailboxes' | 'vboxes'

// ─── Componente principale ────────────────────────────────────────────────────

export function SignaturesPage() {
  const queryClient = useQueryClient()
  const { isAdmin } = useAuth()
  const [activeTab, setActiveTab] = useState<Tab>('library')

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="border-b bg-background px-6 py-4">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-xl font-semibold">Firme automatiche</h1>
            <p className="text-sm text-muted-foreground">
              Gestisci le firme inserite automaticamente nelle PEC inviate
            </p>
          </div>
        </div>

        {/* Tab bar */}
        <div className="flex gap-1 mt-4 border-b -mb-[1px]">
          {[
            { id: 'library' as Tab, label: 'Libreria firme' },
            { id: 'mailboxes' as Tab, label: 'Caselle PEC' },
            { id: 'vboxes' as Tab, label: 'Virtual Box' },
          ].map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
                activeTab === tab.id
                  ? 'border-primary text-primary'
                  : 'border-transparent text-muted-foreground hover:text-foreground'
              }`}
            >
              {tab.label}
            </button>
          ))}
        </div>
      </div>

      {/* Contenuto tab */}
      <div className="flex-1 overflow-y-auto">
        {activeTab === 'library' && <LibraryTab isAdmin={isAdmin} queryClient={queryClient} />}
        {activeTab === 'mailboxes' && <MailboxAssignmentsTab isAdmin={isAdmin} />}
        {activeTab === 'vboxes' && <VboxAssignmentsTab isAdmin={isAdmin} />}
      </div>
    </div>
  )
}

// ─── Tab: Libreria firme ──────────────────────────────────────────────────────

function LibraryTab({ isAdmin, queryClient }: { isAdmin: boolean; queryClient: ReturnType<typeof useQueryClient> }) {
  const [q, setQ] = useState('')
  const [showForm, setShowForm] = useState(false)
  const [editing, setEditing] = useState<SignatureResponse | null>(null)

  // Stato form
  const [formName, setFormName] = useState('')
  const [formDescription, setFormDescription] = useState('')
  const [formBody, setFormBody] = useState('')

  const { data, isLoading } = useQuery({
    queryKey: ['signatures', q],
    queryFn: () => signaturesApi.list(q || undefined),
  })

  const createMutation = useMutation({
    mutationFn: (data: SignatureCreate) => signaturesApi.create(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['signatures'] })
      toast.success('Firma creata')
      closeForm()
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: SignatureCreate }) =>
      signaturesApi.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['signatures'] })
      toast.success('Firma aggiornata')
      closeForm()
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => signaturesApi.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['signatures'] })
      toast.success('Firma eliminata')
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const openCreate = () => {
    setEditing(null)
    setFormName('')
    setFormDescription('')
    setFormBody('')
    setShowForm(true)
  }

  const openEdit = (s: SignatureResponse) => {
    setEditing(s)
    setFormName(s.name)
    setFormDescription(s.description ?? '')
    setFormBody(s.body_html ?? s.body_text ?? '')
    setShowForm(true)
  }

  const closeForm = () => {
    setShowForm(false)
    setEditing(null)
  }

  const handleSubmit = () => {
    if (!formName.trim()) return toast.error('Il nome e\' obbligatorio')
    const payload: SignatureCreate = {
      name: formName.trim(),
      description: formDescription.trim() || null,
      body_html: formBody || null,
      body_text: null,
    }
    if (editing) {
      updateMutation.mutate({ id: editing.id, data: payload })
    } else {
      createMutation.mutate(payload)
    }
  }

  const items = data?.items ?? []

  return (
    <div className="p-6 space-y-4">
      <div className="flex items-center justify-between">
        <div className="relative w-full max-w-sm">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="Cerca per nome..."
            value={q}
            onChange={(e) => setQ(e.target.value)}
            className="pl-9"
          />
        </div>
        {isAdmin && (
          <Button onClick={openCreate}>
            <Plus className="h-4 w-4 mr-2" />
            Nuova firma
          </Button>
        )}
      </div>

      {isLoading ? (
        <div className="flex justify-center py-12">
          <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
        </div>
      ) : items.length === 0 ? (
        <div className="text-center py-12 text-muted-foreground">
          <PenLine className="h-12 w-12 mx-auto mb-4 opacity-30" />
          <p className="text-lg font-medium">Nessuna firma trovata</p>
          <p className="text-sm mt-1">
            {isAdmin
              ? 'Crea la prima firma con il pulsante in alto.'
              : 'Nessuna firma disponibile.'}
          </p>
        </div>
      ) : (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {items.map((s) => (
            <div
              key={s.id}
              className="rounded-lg border bg-card p-4 space-y-2 hover:shadow-sm transition-shadow"
            >
              <div className="flex items-start justify-between gap-2">
                <div className="min-w-0">
                  <h3 className="font-semibold truncate">{s.name}</h3>
                  {s.description && (
                    <p className="text-xs text-muted-foreground line-clamp-2">{s.description}</p>
                  )}
                </div>
                {isAdmin && (
                  <div className="flex gap-1 flex-shrink-0">
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => openEdit(s)}
                      className="h-8 w-8"
                    >
                      <Pencil className="h-3.5 w-3.5" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-8 w-8 text-destructive hover:text-destructive"
                      onClick={() => {
                        if (confirm(`Eliminare la firma "${s.name}"?`)) {
                          deleteMutation.mutate(s.id)
                        }
                      }}
                    >
                      <Trash2 className="h-3.5 w-3.5" />
                    </Button>
                  </div>
                )}
              </div>

              {/* Anteprima corpo */}
              {s.body_html && (
                <div
                  className="text-xs text-muted-foreground border rounded p-2 bg-muted/30 max-h-20 overflow-hidden line-clamp-3"
                  dangerouslySetInnerHTML={{ __html: s.body_html }}
                />
              )}

              <p className="text-xs text-muted-foreground">
                Aggiornato: {formatDate(s.updated_at)}
              </p>
            </div>
          ))}
        </div>
      )}

      {/* Dialog form firma */}
      <Dialog open={showForm} onOpenChange={(o) => !o && closeForm()}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editing ? 'Modifica firma' : 'Nuova firma'}</DialogTitle>
          </DialogHeader>

          <div className="space-y-4 mt-4">
            <div className="space-y-2">
              <Label>Nome *</Label>
              <Input
                value={formName}
                onChange={(e) => setFormName(e.target.value)}
                placeholder="Es. Firma aziendale standard"
              />
            </div>
            <div className="space-y-2">
              <Label>Descrizione (opzionale)</Label>
              <Input
                value={formDescription}
                onChange={(e) => setFormDescription(e.target.value)}
                placeholder="Breve descrizione d'uso"
              />
            </div>
            <div className="space-y-2">
              <Label>Testo della firma</Label>
              <div className="min-h-[200px] border rounded-md overflow-hidden">
                <RichTextEditor
                  value={formBody}
                  onChange={setFormBody}
                  placeholder="Scrivi qui la firma..."
                />
              </div>
            </div>
          </div>

          <DialogFooter className="mt-4">
            <Button variant="outline" onClick={closeForm}>
              Annulla
            </Button>
            <Button
              onClick={handleSubmit}
              isLoading={createMutation.isPending || updateMutation.isPending}
            >
              {editing ? 'Salva modifiche' : 'Crea firma'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}

// ─── Tab: Assegnazioni caselle PEC ────────────────────────────────────────────

function MailboxAssignmentsTab({ isAdmin }: { isAdmin: boolean }) {
  const queryClient = useQueryClient()

  const { data: mailboxesData, isLoading: loadingMailboxes } = useQuery({
    queryKey: ['mailboxes'],
    queryFn: () => mailboxesApi.list(),
  })

  const { data: signaturesData, isLoading: loadingSignatures } = useQuery({
    queryKey: ['signatures', ''],
    queryFn: () => signaturesApi.list(),
  })

  const { data: assignmentsData, isLoading: loadingAssignments } = useQuery({
    queryKey: ['signature-assignments'],
    queryFn: () => signaturesApi.listAssignments(),
  })

  const assignMutation = useMutation({
    mutationFn: signaturesApi.createAssignment,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['signature-assignments'] })
      toast.success('Firma assegnata')
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const removeMutation = useMutation({
    mutationFn: signaturesApi.deleteAssignment,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['signature-assignments'] })
      toast.success('Assegnazione rimossa')
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const mailboxes = mailboxesData?.items ?? []
  const signatures = signaturesData?.items ?? []
  const assignments = assignmentsData?.items ?? []

  // Mappa: mailbox_id + context -> assignment
  const assignmentMap = new Map<string, (typeof assignments)[0]>()
  for (const a of assignments) {
    if (a.mailbox_id) {
      assignmentMap.set(`${a.mailbox_id}:${a.context}`, a)
    }
  }

  const getAssignment = (mailboxId: string, context: SignatureContext) =>
    assignmentMap.get(`${mailboxId}:${context}`) ?? null

  const handleChange = (mailboxId: string, context: SignatureContext, signatureId: string) => {
    if (!signatureId) {
      // Rimuovi assegnazione esistente
      const existing = getAssignment(mailboxId, context)
      if (existing) removeMutation.mutate(existing.id)
    } else {
      assignMutation.mutate({ signature_id: signatureId, mailbox_id: mailboxId, context })
    }
  }

  const isLoading = loadingMailboxes || loadingSignatures || loadingAssignments

  if (isLoading) {
    return (
      <div className="flex justify-center py-12">
        <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
      </div>
    )
  }

  if (mailboxes.length === 0) {
    return (
      <div className="text-center py-12 text-muted-foreground p-6">
        <p className="text-lg font-medium">Nessuna casella PEC configurata</p>
        <p className="text-sm mt-1">Aggiungi prima le caselle PEC nella sezione Caselle PEC.</p>
      </div>
    )
  }

  return (
    <div className="p-6 space-y-4">
      <p className="text-sm text-muted-foreground">
        Assegna una firma per ogni casella PEC e per ogni contesto d'uso.
        {!isAdmin && ' Solo gli amministratori possono modificare le assegnazioni.'}
      </p>

      <div className="rounded-lg border overflow-hidden">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b bg-muted/50">
              <th className="text-left px-4 py-3 font-medium">Casella PEC</th>
              <th className="text-left px-4 py-3 font-medium">Firma per Risposta</th>
              <th className="text-left px-4 py-3 font-medium">Firma per Nuova PEC</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {mailboxes.map((mb) => (
              <MailboxAssignmentRow
                key={mb.id}
                mailboxId={mb.id}
                displayName={mb.display_name || mb.email_address}
                emailAddress={mb.email_address}
                status={mb.status}
                signatures={signatures}
                replyAssignment={getAssignment(mb.id, 'reply')}
                composeAssignment={getAssignment(mb.id, 'compose')}
                isAdmin={isAdmin}
                onChangeReply={(sigId) => handleChange(mb.id, 'reply', sigId)}
                onChangeCompose={(sigId) => handleChange(mb.id, 'compose', sigId)}
                isPending={assignMutation.isPending || removeMutation.isPending}
              />
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}

interface MailboxAssignmentRowProps {
  mailboxId: string
  displayName: string
  emailAddress: string
  status: string
  signatures: SignatureResponse[]
  replyAssignment: { id: string; signature_id: string } | null
  composeAssignment: { id: string; signature_id: string } | null
  isAdmin: boolean
  onChangeReply: (sigId: string) => void
  onChangeCompose: (sigId: string) => void
  isPending: boolean
}

function MailboxAssignmentRow({
  displayName,
  emailAddress,
  status,
  signatures,
  replyAssignment,
  composeAssignment,
  isAdmin,
  onChangeReply,
  onChangeCompose,
  isPending,
}: MailboxAssignmentRowProps) {
  const statusDot =
    status === 'active'
      ? 'bg-green-500'
      : status === 'paused'
      ? 'bg-yellow-400'
      : status === 'error'
      ? 'bg-red-500'
      : 'bg-gray-400'

  return (
    <tr className="hover:bg-muted/30 transition-colors">
      <td className="px-4 py-3">
        <div className="flex items-center gap-2">
          <span className={`h-2 w-2 rounded-full flex-shrink-0 ${statusDot}`} />
          <div>
            <p className="font-medium">{displayName}</p>
            {displayName !== emailAddress && (
              <p className="text-xs text-muted-foreground">{emailAddress}</p>
            )}
          </div>
        </div>
      </td>
      <td className="px-4 py-3">
        <SignatureSelect
          signatures={signatures}
          value={replyAssignment?.signature_id ?? ''}
          onChange={onChangeReply}
          disabled={!isAdmin || isPending}
        />
      </td>
      <td className="px-4 py-3">
        <SignatureSelect
          signatures={signatures}
          value={composeAssignment?.signature_id ?? ''}
          onChange={onChangeCompose}
          disabled={!isAdmin || isPending}
        />
      </td>
    </tr>
  )
}

// ─── Tab: Assegnazioni Virtual Box ────────────────────────────────────────────

function VboxAssignmentsTab({ isAdmin }: { isAdmin: boolean }) {
  const queryClient = useQueryClient()

  const { data: vboxesData, isLoading: loadingVboxes } = useQuery({
    queryKey: ['virtual-boxes', 'all'],
    queryFn: () => virtualBoxesApi.list(),
  })

  const { data: signaturesData, isLoading: loadingSignatures } = useQuery({
    queryKey: ['signatures', ''],
    queryFn: () => signaturesApi.list(),
  })

  const { data: assignmentsData, isLoading: loadingAssignments } = useQuery({
    queryKey: ['signature-assignments'],
    queryFn: () => signaturesApi.listAssignments(),
  })

  const assignMutation = useMutation({
    mutationFn: signaturesApi.createAssignment,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['signature-assignments'] })
      toast.success('Firma assegnata')
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const removeMutation = useMutation({
    mutationFn: signaturesApi.deleteAssignment,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['signature-assignments'] })
      toast.success('Assegnazione rimossa')
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const vboxes = vboxesData?.items ?? []
  const signatures = signaturesData?.items ?? []
  const assignments = assignmentsData?.items ?? []

  // Mappa: virtual_box_id + context -> assignment
  const assignmentMap = new Map<string, (typeof assignments)[0]>()
  for (const a of assignments) {
    if (a.virtual_box_id) {
      assignmentMap.set(`${a.virtual_box_id}:${a.context}`, a)
    }
  }

  const getAssignment = (vboxId: string, context: SignatureContext) =>
    assignmentMap.get(`${vboxId}:${context}`) ?? null

  const handleChange = (vboxId: string, context: SignatureContext, signatureId: string) => {
    if (!signatureId) {
      const existing = getAssignment(vboxId, context)
      if (existing) removeMutation.mutate(existing.id)
    } else {
      assignMutation.mutate({ signature_id: signatureId, virtual_box_id: vboxId, context })
    }
  }

  const isLoading = loadingVboxes || loadingSignatures || loadingAssignments

  if (isLoading) {
    return (
      <div className="flex justify-center py-12">
        <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
      </div>
    )
  }

  if (vboxes.length === 0) {
    return (
      <div className="text-center py-12 text-muted-foreground p-6">
        <p className="text-lg font-medium">Nessuna Virtual Box configurata</p>
        <p className="text-sm mt-1">Aggiungi prima le Virtual Box nella sezione Virtual Box.</p>
      </div>
    )
  }

  return (
    <div className="p-6 space-y-4">
      <p className="text-sm text-muted-foreground">
        Assegna una firma per ogni Virtual Box e per ogni contesto d'uso.
        {!isAdmin && ' Solo gli amministratori possono modificare le assegnazioni.'}
      </p>

      <div className="rounded-lg border overflow-hidden">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b bg-muted/50">
              <th className="text-left px-4 py-3 font-medium">Virtual Box</th>
              <th className="text-left px-4 py-3 font-medium">Firma per Risposta</th>
              <th className="text-left px-4 py-3 font-medium">Firma per Nuova PEC</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {vboxes.map((vbox) => (
              <tr key={vbox.id} className="hover:bg-muted/30 transition-colors">
                <td className="px-4 py-3">
                  <div className="flex items-center gap-2">
                    <div className="h-6 w-6 rounded-full bg-purple-800 flex items-center justify-center text-white text-xs font-semibold flex-shrink-0">
                      {(vbox.label || vbox.name)[0]?.toUpperCase() ?? '?'}
                    </div>
                    <div>
                      <p className="font-medium">{vbox.label || vbox.name}</p>
                      {vbox.description && (
                        <p className="text-xs text-muted-foreground truncate max-w-[200px]">
                          {vbox.description}
                        </p>
                      )}
                    </div>
                  </div>
                </td>
                <td className="px-4 py-3">
                  <SignatureSelect
                    signatures={signatures}
                    value={getAssignment(vbox.id, 'reply')?.signature_id ?? ''}
                    onChange={(sigId) => handleChange(vbox.id, 'reply', sigId)}
                    disabled={!isAdmin || assignMutation.isPending || removeMutation.isPending}
                  />
                </td>
                <td className="px-4 py-3">
                  <SignatureSelect
                    signatures={signatures}
                    value={getAssignment(vbox.id, 'compose')?.signature_id ?? ''}
                    onChange={(sigId) => handleChange(vbox.id, 'compose', sigId)}
                    disabled={!isAdmin || assignMutation.isPending || removeMutation.isPending}
                  />
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}

// ─── Select firma riutilizzabile ──────────────────────────────────────────────

interface SignatureSelectProps {
  signatures: SignatureResponse[]
  value: string
  onChange: (signatureId: string) => void
  disabled?: boolean
}

function SignatureSelect({ signatures, value, onChange, disabled }: SignatureSelectProps) {
  return (
    <select
      className="flex h-8 w-full max-w-[220px] rounded-md border border-input bg-background px-3 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50 disabled:cursor-not-allowed"
      value={value}
      onChange={(e) => onChange(e.target.value)}
      disabled={disabled}
    >
      <option value="">-- Nessuna firma --</option>
      {signatures.map((s) => (
        <option key={s.id} value={s.id}>
          {s.name}
        </option>
      ))}
    </select>
  )
}
