// src/views/components/product/ProductDetails.tsx

import React from 'react'
import {
  Grid,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Button,
  Typography,
  Box,
  FormHelperText,
  Paper,
  IconButton,
  Autocomplete,
} from '@mui/material'
import { Controller, useFieldArray, Control } from 'react-hook-form'
import Icon from 'src/@core/components/icon'
import { countries } from 'src/@fake-db/autocomplete'
import { ProductFormValues, Category, Vendor, Tax } from './types'
import { validateDescription } from './hooks'

interface ProductDetailsProps {
  control: Control<ProductFormValues>
  errors: any
  categories: Category[]
  vendors: Vendor[]
  taxes: Tax[]
  productType: string
  isSubmitting: boolean
  onAddCategory: () => void
  onAddVendor: () => void
  onAddTax: () => void
}

const ProductDetails = ({
  control,
  errors,
  categories,
  vendors,
  taxes,
  productType,
  isSubmitting,
  onAddCategory,
  onAddVendor,
  onAddTax
}: ProductDetailsProps) => {
  const { fields: staffFields, append: appendStaff, remove: removeStaff } = useFieldArray({
    control,
    name: 'staffMembers'
  })

  return (
    <Grid container spacing={4}>
      <Grid item xs={12}>
        <Typography variant='subtitle1' fontWeight={600} sx={{ mb: 2 }}>
          Add New Products details
        </Typography>
      </Grid>

      <Grid item xs={12} md={6}>
        <Controller
          name='productName'
          control={control}
          rules={{ required: 'Product name is required' }}
          render={({ field }) => (
            <TextField
              {...field}
              fullWidth
              label='Product Name *'
              placeholder='Product Name'
              error={!!errors.productName}
              helperText={errors.productName?.message}
              disabled={isSubmitting}
            />
          )}
        />
      </Grid>

      <Grid item xs={12} md={6}>
        <Controller
          name='productType'
          control={control}
          rules={{ required: 'Product type is required' }}
          render={({ field }) => (
            <FormControl fullWidth error={!!errors.productType}>
              <InputLabel>Product Type *</InputLabel>
              <Select {...field} label='Product Type *' disabled={isSubmitting}>
                <MenuItem value='ServiceBased'>Service Based</MenuItem>
                <MenuItem value='ReadyToSell'>Ready To Sell</MenuItem>
                {/* <MenuItem value='Subscription'>Subscription</MenuItem>
                <MenuItem value='RawMaterials'>Raw Materials</MenuItem> */}
              </Select>
              {errors.productType && <FormHelperText>{errors.productType.message}</FormHelperText>}
            </FormControl>
          )}
        />
      </Grid>

      <Grid item xs={12} md={6}>
        <Controller
          name='categoryUid'
          control={control}
          rules={{ required: 'Category is required' }}
          render={({ field }) => (
            <FormControl fullWidth error={!!errors.categoryUid}>
              <InputLabel>Category *</InputLabel>
              <Select
                {...field}
                label='Category *'
                disabled={isSubmitting}
                value={field.value || ''}
              >
                {categories.map((cat) => (
                  <MenuItem key={cat.uid} value={cat.uid}>{cat.name}</MenuItem>
                ))}
              </Select>
              {errors.categoryUid && <FormHelperText>{errors.categoryUid.message}</FormHelperText>}
            </FormControl>
          )}
        />
        <Button
          size='small'
          startIcon={<Icon icon='tabler:plus' />}
          onClick={onAddCategory}
          sx={{ mt: 1 }}
        >
          Add New Category
        </Button>
      </Grid>

      <Grid item xs={12} md={6}>
        <Controller
          name='vendorUid'
          control={control}
          rules={{ required: 'Vendor is required' }}
          render={({ field }) => (
            <FormControl fullWidth error={!!errors.vendorUid}>
              <InputLabel>Vendor *</InputLabel>
              <Select
                {...field}
                label='Vendor *'
                disabled={isSubmitting}
                value={field.value || ''}
              >
                {vendors.map((vendor) => (
                  <MenuItem key={vendor.uid} value={vendor.uid}>{vendor.vendorName}</MenuItem>
                ))}
              </Select>
              {errors.vendorUid && <FormHelperText>{errors.vendorUid.message}</FormHelperText>}
            </FormControl>
          )}
        />
        <Button
          size='small'
          startIcon={<Icon icon='tabler:plus' />}
          onClick={onAddVendor}
          sx={{ mt: 1 }}
        >
          Add New Vendor
        </Button>
      </Grid>

      <Grid item xs={12} md={6}>
        <Controller
          name='taxCharges'
          control={control}
          render={({ field }) => (
            <FormControl fullWidth>
              <InputLabel>Tax Charges</InputLabel>
              <Select {...field} label='Tax Charges' value='Exclusive' disabled>
                <MenuItem value='Exclusive'>Exclusive</MenuItem>
                <MenuItem value='Inclusive'>Inclusive</MenuItem>
              </Select>
              <FormHelperText>Tax charges are fixed to Exclusive</FormHelperText>
            </FormControl>
          )}
        />
      </Grid>

      <Grid item xs={12} md={6}>
        <Controller
          name='taxes'
          control={control}
          render={({ field }) => (
            <FormControl fullWidth>
              <InputLabel>Tax</InputLabel>
              <Select
                {...field}
                label='Tax'
                disabled={isSubmitting}
                value={field.value || ''}
              >
                <MenuItem value=''>None</MenuItem>
                {taxes.map((tax) => {
                  let displayValue = ''
                  if (tax.taxType === 'percentage') {
                    displayValue = `${tax.taxValue}%`
                  } else {
                    displayValue = `${tax.taxValue}$`
                  }
                  return (
                    <MenuItem key={tax.uid} value={tax.uid}>
                      {tax.taxName} - {displayValue}
                    </MenuItem>
                  )
                })}
              </Select>
            </FormControl>
          )}
        />
        <Button
          size='small'
          startIcon={<Icon icon='tabler:plus' />}
          onClick={onAddTax}
          sx={{ mt: 1 }}
        >
          Add New Tax
        </Button>
      </Grid>

      <Grid item xs={12}>
        <Controller
          name='description'
          control={control}
          rules={{
            maxLength: { value: 500, message: 'Maximum 500 characters' },
            validate: (value) => {
              if (value && !validateDescription(value)) {
                return 'Description can only contain letters, numbers, spaces, and special characters .,-'
              }
              return true
            }
          }}
          render={({ field }) => (
            <TextField
              {...field}
              fullWidth
              multiline
              rows={4}
              label='Description optional (max 500 characters)'
              placeholder='Description'
              error={!!errors.description}
              helperText={errors.description?.message || `${field.value?.length || 0}/500`}
              disabled={isSubmitting}
            />
          )}
        />
      </Grid>

      {productType === 'ServiceBased' && (
        <Grid item xs={12}>
          <Box sx={{ mt: 2 }}>
            <Typography variant='subtitle1' fontWeight={600} sx={{ mb: 2 }}>
              Staff Members
            </Typography>
            {staffFields.map((field, index) => (
              <Paper key={field.id} sx={{ p: 3, mb: 2, position: 'relative', overflow: 'visible' }}>
                {staffFields.length > 1 && (
                  <IconButton
                    size='small'
                    color='error'
                    onClick={() => removeStaff(index)}
                    sx={{
                      position: 'absolute',
                      top: -10,
                      right: -10,
                      zIndex: 1,
                      bgcolor: 'background.paper',
                      border: '1px solid',
                      borderColor: 'divider',
                      '&:hover': { bgcolor: 'error.light' }
                    }}
                  >
                    <Icon icon='tabler:x' fontSize={16} />
                  </IconButton>
                )}
                <Grid container spacing={3}>
                  <Grid item xs={12} md={6}>
                    <Controller
                      name={`staffMembers.${index}.firstName`}
                      control={control}
                      rules={{ required: 'First name is required' }}
                      render={({ field }) => (
                        <TextField
                          {...field}
                          fullWidth
                          label='First Name *'
                          size='small'
                          error={!!errors.staffMembers?.[index]?.firstName}
                          helperText={errors.staffMembers?.[index]?.firstName?.message}
                          disabled={isSubmitting}
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12} md={6}>
                    <Controller
                      name={`staffMembers.${index}.lastName`}
                      control={control}
                      rules={{ required: 'Last name is required' }}
                      render={({ field }) => (
                        <TextField
                          {...field}
                          fullWidth
                          label='Last Name *'
                          size='small'
                          error={!!errors.staffMembers?.[index]?.lastName}
                          helperText={errors.staffMembers?.[index]?.lastName?.message}
                          disabled={isSubmitting}
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12} md={6}>
                    <Controller
                      name={`staffMembers.${index}.email`}
                      control={control}
                      rules={{
                        required: 'Email is required',
                        pattern: {
                          value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
                          message: 'Invalid email address'
                        }
                      }}
                      render={({ field }) => (
                        <TextField
                          {...field}
                          fullWidth
                          label='Email ID *'
                          size='small'
                          error={!!errors.staffMembers?.[index]?.email}
                          helperText={errors.staffMembers?.[index]?.email?.message}
                          disabled={isSubmitting}
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12} md={6}>
                    <Controller
                      name={`staffMembers.${index}.phoneNumber`}
                      control={control}
                      rules={{ required: 'Phone number is required' }}
                      render={({ field: phoneField }) => (
                        <Controller
                          name={`staffMembers.${index}.dialCodeCountry`}
                          control={control}
                          render={({ field: countryField }) => (
                            <Box sx={{ display: 'flex', gap: 2, alignItems: 'flex-start' }}>
                              <Autocomplete
                                sx={{ width: '200px' }}
                                options={countries}
                                autoHighlight
                                getOptionLabel={(option) => `${option.code} +${option.phone}`}
                                value={countries.find(c => c.code === countryField.value) || null}
                                onChange={(_, newValue) => {
                                  if (newValue) {
                                    countryField.onChange(newValue.code)
                                  }
                                }}
                                renderOption={(props, option) => (
                                  <Box component="li" sx={{ '& > img': { mr: 2, flexShrink: 0 } }} {...props}>
                                    <img
                                      loading="lazy"
                                      width="20"
                                      src={`https://flagcdn.com/w20/${option.code.toLowerCase()}.png`}
                                      srcSet={`https://flagcdn.com/w40/${option.code.toLowerCase()}.png 2x`}
                                      alt=""
                                      style={{ marginRight: '8px' }}
                                    />
                                    {option.label} ({option.code}) +{option.phone}
                                  </Box>
                                )}
                                renderInput={(params) => (
                                  <TextField
                                    {...params}
                                    label="Country Code"
                                    size='small'
                                    error={!!errors.staffMembers?.[index]?.dialCodeCountry}
                                    helperText={errors.staffMembers?.[index]?.dialCodeCountry?.message}
                                    disabled={isSubmitting}
                                    inputProps={{
                                      ...params.inputProps,
                                      autoComplete: 'new-password',
                                    }}
                                  />
                                )}
                              />
                              <TextField
                                {...phoneField}
                                fullWidth
                                label='Phone Number *'
                                placeholder='555 000 0000'
                                size='small'
                                error={!!errors.staffMembers?.[index]?.phoneNumber}
                                helperText={errors.staffMembers?.[index]?.phoneNumber?.message}
                                disabled={isSubmitting}
                              />
                            </Box>
                          )}
                        />
                      )}
                    />
                  </Grid>
                </Grid>
              </Paper>
            ))}
            <Button
              variant='outlined'
              startIcon={<Icon icon='tabler:plus' />}
              onClick={() => appendStaff({ firstName: '', lastName: '', email: '', phoneNumber: '', countryCode: '+1', dialCodeCountry: 'US' })}
              disabled={isSubmitting}
            >
              Add Staff Member
            </Button>
          </Box>
        </Grid>
      )}
    </Grid>
  )
}

export default ProductDetails