import {
  mdiFileExportOutline,
  mdiPackageVariantClosed,
  mdiAccountGroupOutline,
  mdiTruckOutline,
  mdiWarehouse,
  mdiChevronRight,
  mdiChevronLeft,
  mdiDownload,
} from '@mdi/js'
import Head from 'next/head'
import React, { ReactElement, useState } from 'react'
import CardBox from '../components/CardBox'
import LayoutAuthenticated from '../layouts/Authenticated'
import SectionMain from '../components/SectionMain'
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton'
import { getPageTitle } from '../config'
import BaseButton from '../components/BaseButton'
import BaseButtons from '../components/BaseButtons'
import FormField from '../components/FormField'
import axios from 'axios'
import BaseIcon from '../components/BaseIcon'

const entities = [
  { id: 'products', label: 'Products', icon: mdiPackageVariantClosed, fields: ['id', 'tenant', 'sku', 'name', 'description', 'uom', 'currency', 'price'] },
  { id: 'customers', label: 'Customers', icon: mdiAccountGroupOutline, fields: ['id', 'tenant', 'customer_code', 'name', 'email', 'phone', 'billing_address', 'shipping_address'] },
  { id: 'suppliers', label: 'Suppliers', icon: mdiTruckOutline, fields: ['id', 'tenant', 'supplier_code', 'name', 'email', 'phone', 'address'] },
  { id: 'availability_records', label: 'Availability records', icon: mdiWarehouse, fields: ['id', 'tenant', 'location_code', 'product_sku', 'source_reference', 'quantity_on_hand', 'quantity_available', 'as_of'] },
]

const ExportWizard = () => {
  const [step, setStep] = useState(1)
  const [selectedEntity, setSelectedEntity] = useState('')
  const [selectedFields, setSelectedFields] = useState<string[]>([])

  const currentEntity = entities.find((e) => e.id === selectedEntity)

  const handleEntitySelect = (entityId: string) => {
    setSelectedEntity(entityId)
    const entity = entities.find((e) => e.id === entityId)
    if (entity) {
      setSelectedFields(entity.fields)
    }
    setStep(2)
  }

  const toggleField = (field: string) => {
    if (selectedFields.includes(field)) {
      setSelectedFields(selectedFields.filter((f) => f !== field))
    } else {
      setSelectedFields([...selectedFields, field])
    }
  }

  const handleExport = async () => {
    try {
      const response = await axios.get(`/${selectedEntity}`, {
        params: {
          filetype: 'xlsx',
          fields: selectedFields.join(','),
        },
        responseType: 'blob',
      })
      const url = window.URL.createObjectURL(new Blob([response.data]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', `${selectedEntity}_export_${new Date().toISOString().split('T')[0]}.xlsx`)
      document.body.appendChild(link)
      link.click()
      link.remove()
    } catch (error) {
      console.error('Export failed', error)
      alert('Export failed. Please try again.')
    }
  }

  return (
    <>
      <Head>
        <title>{getPageTitle('Export Wizard')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiFileExportOutline} title="Export Wizard" main>
          {''}
        </SectionTitleLineWithButton>

        <CardBox className="mb-6">
          <div className="flex items-center justify-between mb-8">
            <div className={`flex flex-col items-center ${step >= 1 ? 'text-blue-600' : 'text-gray-400'}`}>
              <div className={`w-10 h-10 rounded-full flex items-center justify-center border-2 ${step >= 1 ? 'border-blue-600 bg-blue-50' : 'border-gray-300'}`}>1</div>
              <span className="text-xs mt-1 font-bold">Select Entity</span>
            </div>
            <div className={`flex-1 h-1 mx-4 ${step >= 2 ? 'bg-blue-600' : 'bg-gray-200'}`}></div>
            <div className={`flex flex-col items-center ${step >= 2 ? 'text-blue-600' : 'text-gray-400'}`}>
              <div className={`w-10 h-10 rounded-full flex items-center justify-center border-2 ${step >= 2 ? 'border-blue-600 bg-blue-50' : 'border-gray-300'}`}>2</div>
              <span className="text-xs mt-1 font-bold">Select Fields</span>
            </div>
            <div className={`flex-1 h-1 mx-4 ${step >= 3 ? 'bg-blue-600' : 'bg-gray-200'}`}></div>
            <div className={`flex flex-col items-center ${step >= 3 ? 'text-blue-600' : 'text-gray-400'}`}>
              <div className={`w-10 h-10 rounded-full flex items-center justify-center border-2 ${step >= 3 ? 'border-blue-600 bg-blue-50' : 'border-gray-300'}`}>3</div>
              <span className="text-xs mt-1 font-bold">Download</span>
            </div>
          </div>

          {step === 1 && (
            <div>
              <h2 className="text-xl font-bold mb-4">What would you like to export?</h2>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                {entities.map((entity) => (
                  <div
                    key={entity.id}
                    onClick={() => handleEntitySelect(entity.id)}
                    className="p-6 border-2 rounded-lg cursor-pointer hover:border-blue-500 hover:bg-blue-50 transition-colors flex flex-col items-center text-center group"
                  >
                    <BaseIcon path={entity.icon} size={48} className="mb-4 text-gray-500 group-hover:text-blue-500" />
                    <span className="font-bold">{entity.label}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {step === 2 && currentEntity && (
            <div>
              <div className="flex items-center mb-4">
                <BaseIcon path={currentEntity.icon} className="mr-2" />
                <h2 className="text-xl font-bold">Select fields for {currentEntity.label}</h2>
              </div>
              <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 mb-8">
                {currentEntity.fields.map((field) => (
                  <label key={field} className="flex items-center space-x-3 p-3 border rounded hover:bg-gray-50 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={selectedFields.includes(field)}
                      onChange={() => toggleField(field)}
                      className="form-checkbox h-5 w-5 text-blue-600"
                    />
                    <span className="capitalize">{field.replace('_', ' ')}</span>
                  </label>
                ))}
              </div>
              <BaseButtons>
                <BaseButton label="Back" icon={mdiChevronLeft} onClick={() => setStep(1)} />
                <BaseButton label="Next" color="info" icon={mdiChevronRight} onClick={() => setStep(3)} disabled={selectedFields.length === 0} />
              </BaseButtons>
            </div>
          )}

          {step === 3 && currentEntity && (
            <div className="text-center py-8">
              <BaseIcon path={mdiDownload} size={64} className="mb-4 text-blue-500 mx-auto" />
              <h2 className="text-2xl font-bold mb-2">Ready to export!</h2>
              <p className="text-gray-500 mb-8">
                You are about to export <strong>{currentEntity.label}</strong> with <strong>{selectedFields.length}</strong> fields.
              </p>
              <BaseButtons className="justify-center">
                <BaseButton label="Back" icon={mdiChevronLeft} onClick={() => setStep(2)} />
                <BaseButton label="Download XLSX" color="success" icon={mdiDownload} onClick={handleExport} />
              </BaseButtons>
            </div>
          )}
        </CardBox>
      </SectionMain>
    </>
  )
}

ExportWizard.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>
}

export default ExportWizard
