'use client'

import { Button } from '@/components/ui/button'
import { useState } from 'react'
import { Input } from '../settings/pw'
import { Label } from '@/components/ui/label'
import { TemplatePicker } from './TemplatePicker'
import { toast as noti } from 'sonner'
import { RefreshCcw } from 'lucide-react'

export default function Page () {
  const [selectedTemplate, setSelectedTemplate] = useState('')
  const [emailTo, setEmailTo] = useState('')
  const [emailFrom, setEmailFrom] = useState('')
  const [rep, setRep] = useState('')
  const [caseId, setCaseId] = useState('')
  const [link, setLink] = useState('')
  const [loading, setLoading] = useState(false)
  const [iframeKey, setIframeKey] = useState(0)

  const handleSendEmail = async () => {
    if (!emailFrom || !emailTo) {
      noti('Error', {
        description: 'Both From and To email fields are required.'
      })
      return
    }
    setLoading(true)
    try {
      const response = await fetch('/api/mail', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          emailto: emailTo,
          subject: emailFrom,
          tmpl: selectedTemplate,
          caseid: caseId,
          rep: rep,
          link: link
        })
      })
      const result = await response.json()
      noti('Success!', {
        description: result.message
      })
    } catch (error) {
      console.error('Error sending email', error)
    }
    setLoading(false)
  }

  return (
    <div className='flex flex-col md:flex-row gap-4 w-full p-4 md:max-h-[900px]'>
      <div className='flex flex-col w-full p-4 border rounded-md gap-4'>
        <p className='font-semibold leading-none tracking-tight'>Mail sender</p>

        <TemplatePicker
          value={selectedTemplate}
          setValue={setSelectedTemplate}
        />
        <div className='flex flex-col gap-2'>
          <Label htmlFor='to'>Send To</Label>
          <Input
            type='email'
            id='to'
            required
            placeholder='Recipient Email'
            className='border p-2 rounded mb-2'
            value={emailTo}
            onChange={e => setEmailTo(e.target.value)}
          />
        </div>
        <div className='flex flex-col gap-2'>
          <Label htmlFor='from'>Subject</Label>
          <Input
            type='text'
            id='from'
            required
            placeholder='Subject'
            className='border p-2 rounded mb-2'
            value={emailFrom}
            onChange={e => setEmailFrom(e.target.value)}
          />
        </div>
        <div className='flex flex-col gap-2'>
          <Label htmlFor='csid'>Case ID</Label>
          <Input
            type='text'
            id='csid'
            placeholder='Case ID'
            className='border p-2 rounded mb-2'
            value={caseId}
            onChange={e => setCaseId(e.target.value)}
          />
        </div>
        <div className='flex flex-col gap-2'>
          <Label htmlFor='rep'>Representative</Label>
          <Input
            type='text'
            id='rep'
            placeholder='Worker name'
            className='border p-2 rounded mb-2'
            value={rep}
            onChange={e => setRep(e.target.value)}
          />
        </div>
        <div className='flex flex-col gap-2'>
          <Label htmlFor='link'>Link</Label>
          <Input
            type='text'
            id='link'
            placeholder='Link'
            className='border p-2 rounded mb-2'
            value={link}
            onChange={e => setLink(e.target.value)}
          />
        </div>
        <Button
          className='bg-foreground'
          onClick={handleSendEmail}
          disabled={loading || !emailFrom || !emailTo}
        >
          {loading ?? (
            <div className='spinner' data-astro-cid-jlpqxutv=''>
              <svg
                width='24'
                height='24'
                viewBox='0 0 24 24'
                xmlns='http://www.w3.org/2000/svg'
                data-astro-cid-jlpqxutv=''
              >
                <g className='spinner-circle' data-astro-cid-jlpqxutv=''>
                  {[...Array(10)].map((_, i) => (
                    <rect
                      key={i}
                      x='11'
                      y='1'
                      width='2'
                      height='6'
                      transform={`rotate(${i * 36} 12 12)`}
                      data-astro-cid-jlpqxutv=''
                      opacity={`${i / 10}`}
                    />
                  ))}
                </g>
              </svg>
            </div>
          )}
          {loading ? 'Sending...' : 'Send Email'}
        </Button>
      </div>
      <div className='flex flex-col w-full relative'>
        <button
          className='absolute bottom-3 right-3 p-2 rounded-md border backdrop-blur-sm bg-accent/90'
          onClick={() => setIframeKey(prev => prev + 1)}
        >
          <RefreshCcw className='w-4 h-4' />
        </button>
        <div className='flex rounded-md bg-card w-full h-full border items-center justify-center'>
          {loading ? (
            <div className='spinner' data-astro-cid-jlpqxutv=''>
              <svg
                width='24'
                height='24'
                viewBox='0 0 24 24'
                xmlns='http://www.w3.org/2000/svg'
                data-astro-cid-jlpqxutv=''
              >
                <g className='spinner-circle' data-astro-cid-jlpqxutv=''>
                  {[...Array(10)].map((_, i) => (
                    <rect
                      key={i}
                      x='11'
                      y='1'
                      width='2'
                      height='6'
                      transform={`rotate(${i * 36} 12 12)`}
                      data-astro-cid-jlpqxutv=''
                      opacity={`${i / 10}`}
                    />
                  ))}
                </g>
              </svg>
            </div>
          ) : selectedTemplate ? (
            <iframe
              key={iframeKey}
              className='w-full h-full rounded-md'
              src={`/api/mail?tmpid=${selectedTemplate}&caseid=${caseId}&link=${link}&rep=${rep}`}
            />
          ) : (
            <p className='text-gray-500'>Select a template to preview</p>
          )}
        </div>
      </div>
    </div>
  )
}
