import React, { useState, useEffect } from 'react'
import LetterOptions from './LetterOptions'
import Button from './Button'
import Preview from './Preview'
import LatestList from './LatestList'
import { generatePdf, getLatest, removeLatest } from './apiHelper'
import { ILatest } from '../interfaces/ILatest'
import { IDocProps } from '../interfaces/IDocProps'

//import './App.css';

export default function App() {
  const [options, setOptions] = useState<IDocProps>({
    address: 'Max Mustermann\nMusterstrasse\n12345 Musterstadt',
    body: 'Inhalt des Briefs',
    closing: 'Mit freundlichen Grüßen',
    customer: '',
    date: new Date().toLocaleDateString('de-DE'),
    enclosing: '',
    invoice: '',
    myRef: '',
    opening: 'Sehr geehrte Damen und Herren',
    ps: '',
    signature: '',
    specialMail: '',
    subject: 'Betreffzeile',
    template: 'brief-fam',
    yourMail: '',
    yourRef: '',
    yourRefName: '',
  })
  const [latest, setLatest] = useState<ILatest[]>([])
  const [pdfUrl, setPdfUrl] = useState<string | null>(null)
  const [pdfIsLoading, setPdfIsLoading] = useState<boolean>(false)
  const [pdfError, setPdfError] = useState<string | null>(null)

  useEffect(() => {
    getLatest()
      .then((latest) => setLatest(latest))
      .catch((err) => console.error('Unable to get latest:', err))
  }, [pdfUrl])

  const _onChange = (name: string, event: React.ChangeEvent<{ value: string }>) => {
    if (!name) {
      return
    }
    const value = event && event.target && event.target.value
    setOptions({ ...options, [name]: value })
  }

  const _onSelectLatest = (selectedOption: ILatest) => {
    setOptions({ ...selectedOption })
  }

  const _onRemoveLatest = (item: ILatest) => {
    removeLatest(item).then(() => setLatest(latest.filter((curr) => curr.id !== item.id)))
  }

  const _onClear = () => {
    window.location.reload()
  }

  const _onGenerate = () => {
    setPdfIsLoading(true)
    setPdfError(null)

    generatePdf(options)
      .then((data) => {
        const { id } = data

        setPdfIsLoading(false)
        setPdfUrl(`/api/pdf/${id}`)
      })
      .catch((error) => {
        setPdfIsLoading(false)
        setPdfError(error.message)
        setPdfUrl(null)
      })
  }

  return (
    <div className="flex flex-col space-x-5 py-3 sm:px-2 lg:px-3 bg-gray-100">
      <div className="flex space-x-5">
        <div className=" flex-grow flex flex-col shadow sm:rounded-md sm:overflow-hidden">
          <LetterOptions onChange={_onChange} {...options} />
          <div className="flex space-x-3 p-3">
            <Button onClick={_onGenerate}>PDF Erstellen</Button>
            <Button onClick={_onClear}>Alles Löschen</Button>
          </div>
        </div>
        <LatestList latest={latest} onSelect={_onSelectLatest} onRemove={_onRemoveLatest} />
      </div>
      <div className="flex flex-col space-y-5">
        <Preview pdfUrl={pdfUrl} pdfIsLoading={pdfIsLoading} pdfError={pdfError} />
      </div>
    </div>
  )
}
