'use client'

import React from 'react'
import { Button, Switch, FormControlLabel, Box, Typography } from '@mui/material'
import Grid from '@mui/material/Grid2'
import CustomAutocomplete from '@/@core/components/mui/Autocomplete'
import CustomTextField from '@/@core/components/mui/TextField'
import { DropdownOption, PurchaseOrderFormData } from '@/types/apps/purchaseOrderTypes'
import { useVendorActive } from '@/services/queries/vendor'

interface PurchaseBasicInfoProps {
  formData: PurchaseOrderFormData
  handleInputChange: (field: keyof PurchaseOrderFormData, value: any) => void
}

const PurchaseBasicInfo: React.FC<PurchaseBasicInfoProps> = ({ formData, handleInputChange }) => {
  const { data: vendors, isLoading } = useVendorActive()

  // Transform vendors data to dropdown options
  const vendorOptions: DropdownOption[] =
    vendors?.map(vendor => ({
      label: vendor.name,
      value: vendor.id
    })) || []

  // Function to get selected vendor data
  const getSelectedVendorData = () => {
    if (!formData.vendor?.value || !vendors) return null

    const selectedVendor = vendors.find(vendor => vendor.id === (formData?.vendor?.value ?? ''))
    return selectedVendor
  }

  const terminOptions: DropdownOption[] = [
    { label: 'Net 30', value: 'net_30' },
    { label: 'Net 15', value: 'net_15' },
    { label: 'Net 60', value: 'net_60' },
    { label: 'Cash on Delivery', value: 'cod' }
  ]

  const ekspedisiOptions: DropdownOption[] = [
    { label: 'JNE', value: 'jne' },
    { label: 'J&T Express', value: 'jnt' },
    { label: 'SiCepat', value: 'sicepat' },
    { label: 'Pos Indonesia', value: 'pos' },
    { label: 'TIKI', value: 'tiki' }
  ]

  return (
    <>
      {/* Row 1 - Vendor dan Nomor */}
      <Grid size={{ xs: 12, sm: 6, md: 6 }}>
        <CustomAutocomplete
          fullWidth
          options={vendorOptions}
          value={formData.vendor}
          onChange={(event, newValue) => {
            handleInputChange('vendor', newValue)

            // Optional: Bisa langsung akses full data vendor saat berubah
            if (newValue?.value) {
              const selectedVendorData = vendors?.find(vendor => vendor.id === newValue.value)
              console.log('Vendor selected:', selectedVendorData)
              // Atau bisa trigger callback lain jika dibutuhkan
            }
          }}
          loading={isLoading}
          renderInput={params => (
            <CustomTextField
              {...params}
              label='Vendor'
              placeholder={isLoading ? 'Loading vendors...' : 'Pilih kontak'}
              fullWidth
            />
          )}
        />
        {getSelectedVendorData() && (
          <Box className='space-y-1 mt-3'>
            {/* Nama Perum */}
            <Box className='flex items-center space-x-2'>
              <i className='tabler-user text-gray-500 w-3 h-3' />
              <Typography className='text-gray-700 font-medium text-xs'>
                {getSelectedVendorData()?.contact_person ?? ''}
              </Typography>
            </Box>

            {/* Alamat */}
            <Box className='flex items-start space-x-2'>
              <i className='tabler-map text-gray-500 w-3 h-3' />
              <Typography className='text-gray-700 font-medium text-xs'>
                {getSelectedVendorData()?.address ?? '-'}
              </Typography>
            </Box>

            {/* Nomor Telepon */}
            <Box className='flex items-center space-x-2'>
              <i className='tabler-phone text-gray-500 w-3 h-3' />
              <Typography className='text-gray-700 font-medium text-xs'>
                {getSelectedVendorData()?.phone_number ?? '-'}
              </Typography>
            </Box>
          </Box>
        )}
      </Grid>
      <Grid size={{ xs: 12, sm: 6, md: 6 }}>
        <CustomTextField
          fullWidth
          label='Nomor'
          value={formData.nomor}
          onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleInputChange('nomor', e.target.value)}
          InputProps={{
            readOnly: true
          }}
        />
      </Grid>

      {/* Row 2 - Tgl. Transaksi, Tgl. Jatuh Tempo, Termin */}
      <Grid size={{ xs: 12, sm: 4, md: 4 }}>
        <CustomTextField
          fullWidth
          label='Tgl. Transaksi'
          type='date'
          value={formData.tglTransaksi}
          onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleInputChange('tglTransaksi', e.target.value)}
          InputLabelProps={{
            shrink: true
          }}
        />
      </Grid>
      <Grid size={{ xs: 12, sm: 4, md: 4 }}>
        <CustomTextField
          fullWidth
          label='Tgl. Jatuh Tempo'
          type='date'
          value={formData.tglJatuhTempo}
          onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleInputChange('tglJatuhTempo', e.target.value)}
          InputLabelProps={{
            shrink: true
          }}
        />
      </Grid>
      <Grid size={{ xs: 12, sm: 4, md: 4 }}>
        <CustomAutocomplete
          fullWidth
          options={terminOptions}
          value={formData.termin}
          onChange={(event, newValue) => handleInputChange('termin', newValue)}
          renderInput={params => <CustomTextField {...params} label='Termin' placeholder='Net 30' fullWidth />}
        />
      </Grid>

      {/* Row 3 - Tampilkan Informasi Pengiriman */}
      <Grid size={12}>
        <Button
          variant='text'
          color='primary'
          onClick={() => handleInputChange('showShippingInfo', !formData.showShippingInfo)}
          sx={{
            textTransform: 'none',
            fontSize: '14px',
            fontWeight: 500,
            padding: '8px 0',
            display: 'flex',
            alignItems: 'center',
            gap: 1
          }}
        >
          {formData.showShippingInfo ? '−' : '+'} {formData.showShippingInfo ? 'Sembunyikan' : 'Tampilkan'} Informasi
          Pengiriman
        </Button>
      </Grid>

      {/* Shipping Information - Conditional */}
      {formData.showShippingInfo && (
        <>
          <Grid size={{ xs: 12, sm: 4, md: 4 }}>
            <CustomTextField
              fullWidth
              label='Tanggal Pengiriman'
              type='date'
              placeholder='Pilih tanggal'
              value={formData.tanggalPengiriman}
              onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                handleInputChange('tanggalPengiriman', e.target.value)
              }
              InputLabelProps={{
                shrink: true
              }}
            />
          </Grid>
          <Grid size={{ xs: 12, sm: 4, md: 4 }}>
            <CustomAutocomplete
              fullWidth
              options={ekspedisiOptions}
              value={formData.ekspedisi}
              onChange={(event, newValue) => handleInputChange('ekspedisi', newValue)}
              renderInput={params => (
                <CustomTextField {...params} label='Ekspedisi' placeholder='Pilih ekspedisi' fullWidth />
              )}
            />
          </Grid>
          <Grid size={{ xs: 12, sm: 4, md: 4 }}>
            <CustomTextField
              fullWidth
              label='No. Resi'
              placeholder='No. Resi'
              value={formData.noResi}
              onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleInputChange('noResi', e.target.value)}
            />
          </Grid>
        </>
      )}

      {/* Row 4 - Referensi, SKU, Switch Pajak */}
      <Grid size={{ xs: 12, sm: 4, md: 4 }}>
        <CustomTextField
          fullWidth
          label='Referensi'
          placeholder='Referensi'
          value={formData.referensi}
          onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleInputChange('referensi', e.target.value)}
        />
      </Grid>
      <Grid size={{ xs: 12, sm: 4, md: 4 }}>
        <CustomTextField fullWidth label='SKU' placeholder='Scan Barcode/SKU' variant='outlined' />
      </Grid>
      <Grid size={{ xs: 12, sm: 4, md: 4 }} sx={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
        <FormControlLabel
          control={
            <Switch
              checked={formData.hargaTermasukPajak}
              onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                handleInputChange('hargaTermasukPajak', e.target.checked)
              }
              color='primary'
            />
          }
          label='Harga termasuk pajak'
          sx={{
            marginLeft: 0,
            '& .MuiFormControlLabel-label': {
              fontSize: '14px',
              color: 'text.secondary'
            }
          }}
        />
      </Grid>
    </>
  )
}

export default PurchaseBasicInfo
