'use client'

import { useState } from 'react'
import { trpc } from '@/lib/trpc/client'
import { toast } from 'sonner'
import { XCircle } from 'lucide-react'
import { Switch } from '@/components/ui/switch'
import { Label } from '@/components/ui/label'
import { EmailPreviewDialog } from './email-preview-dialog'

interface NotifyRejectedButtonProps {
  roundId: string
}

export function NotifyRejectedButton({ roundId }: NotifyRejectedButtonProps) {
  const [open, setOpen] = useState(false)
  const [customMessage, setCustomMessage] = useState<string | undefined>()
  const [fullCustomBody, setFullCustomBody] = useState(false)

  const preview = trpc.round.previewRejectionEmail.useQuery(
    { roundId, customMessage, fullCustomBody },
    { enabled: open }
  )

  const sendMutation = trpc.round.sendRejectionNotifications.useMutation({
    onSuccess: (data) => {
      toast.success(
        `Sent ${data.sent} notification${data.sent !== 1 ? 's' : ''}${data.failed ? ` (${data.failed} failed)` : ''}`
      )
      setOpen(false)
    },
    onError: (err) => toast.error(err.message),
  })

  return (
    <>
      <div className="space-y-2">
        <button
          onClick={() => setOpen(true)}
          className="flex items-start gap-3 p-4 rounded-lg border border-l-4 border-l-red-500 hover:-translate-y-0.5 hover:shadow-md transition-all text-left w-full"
        >
          <XCircle className="h-5 w-5 text-red-600 mt-0.5 shrink-0" />
          <div>
            <p className="text-sm font-medium">Notify Non-Advanced</p>
            <p className="text-xs text-muted-foreground mt-0.5">
              Send rejection emails to non-advanced projects
            </p>
          </div>
        </button>
        <div className="flex items-center gap-2 px-1">
          <Switch
            id="rejection-full-custom-body"
            checked={fullCustomBody}
            onCheckedChange={setFullCustomBody}
          />
          <Label htmlFor="rejection-full-custom-body" className="text-xs cursor-pointer">
            <span className="font-medium">Full custom body</span>
            <span className="text-muted-foreground ml-1">— only your message is sent (no standard text)</span>
          </Label>
        </div>
      </div>

      <EmailPreviewDialog
        open={open}
        onOpenChange={setOpen}
        title="Notify Non-Advanced Teams"
        description="Send rejection notification emails to project team members"
        recipientCount={preview.data?.recipientCount ?? 0}
        previewHtml={preview.data?.html}
        isPreviewLoading={preview.isLoading}
        onSend={(msg) => sendMutation.mutate({ roundId, customMessage: msg, fullCustomBody })}
        isSending={sendMutation.isPending}
        onRefreshPreview={(msg) => setCustomMessage(msg)}
      />
    </>
  )
}
