'use client'

// React Imports
import type { ChangeEvent } from 'react'
import { useState, useEffect } from 'react'

// MUI Imports
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import Typography from '@mui/material/Typography'
import Button from '@mui/material/Button'
import Grid from '@mui/material/Grid2'
import MenuItem from '@mui/material/MenuItem'
import Avatar from '@mui/material/Avatar'
import Divider from '@mui/material/Divider'
import Chip from '@mui/material/Chip'
import Alert from '@mui/material/Alert'
import CircularProgress from '@mui/material/CircularProgress'

// Third-party Imports
import classnames from 'classnames'

// Type Imports
import type { CustomInputHorizontalData } from '@core/components/custom-inputs/types'

// Component Imports
import CustomInputHorizontal from '@core/components/custom-inputs/Horizontal'
import DirectionalIcon from '@components/DirectionalIcon'
import { useSettings } from '@core/hooks/useSettings'
import CustomTextField from '@core/components/mui/TextField'

// Styles Imports
import frontCommonStyles from '@views/front-pages/styles.module.css'
import { useOrganizationsMutation } from '../../../../../services/mutations/organization'
import { useRouter } from 'next/navigation'

// Types
export interface OrganizationRequest {
  organization_name: string
  organization_email?: string | null
  organization_phone_number?: string | null
  plan_type: 'basic' | 'premium' | 'enterprise'
  admin_name: string
  admin_email: string
  admin_password: string
  outlet_name: string
  outlet_address?: string | null
  outlet_timezone?: string | null
  outlet_currency: string
}

// Data
const planData: CustomInputHorizontalData[] = [
  {
    title: (
      <div className='flex items-center gap-4'>
        <Avatar
          variant='rounded'
          className='is-[58px] bs-[34px]'
          sx={theme => ({
            backgroundColor: 'var(--mui-palette-primary-light)',
            color: 'var(--mui-palette-primary-main)'
          })}
        >
          <i className='tabler-rocket text-2xl' />
        </Avatar>
        <div className='flex flex-col'>
          <Typography color='text.primary' className='font-medium'>
            Basic Plan
          </Typography>
          <Typography variant='body2' color='text.secondary'>
            Perfect for small businesses
          </Typography>
        </div>
      </div>
    ),
    value: 'basic',
    isSelected: true
  },
  {
    title: (
      <div className='flex items-center gap-4'>
        <Avatar
          variant='rounded'
          className='is-[58px] bs-[34px]'
          sx={theme => ({
            backgroundColor: 'var(--mui-palette-success-light)',
            color: 'var(--mui-palette-success-main)'
          })}
        >
          <i className='tabler-crown text-2xl' />
        </Avatar>
        <div className='flex flex-col'>
          <Typography color='text.primary' className='font-medium'>
            Premium Plan
          </Typography>
          <Typography variant='body2' color='text.secondary'>
            Most popular choice
          </Typography>
        </div>
      </div>
    ),
    value: 'premium'
  },
  {
    title: (
      <div className='flex items-center gap-4'>
        <Avatar
          variant='rounded'
          className='is-[58px] bs-[34px]'
          sx={theme => ({
            backgroundColor: 'var(--mui-palette-warning-light)',
            color: 'var(--mui-palette-warning-main)'
          })}
        >
          <i className='tabler-building text-2xl' />
        </Avatar>
        <div className='flex flex-col'>
          <Typography color='text.primary' className='font-medium'>
            Enterprise Plan
          </Typography>
          <Typography variant='body2' color='text.secondary'>
            Advanced features for large teams
          </Typography>
        </div>
      </div>
    ),
    value: 'enterprise'
  }
]

const currencies = [
  { code: 'USD', name: 'US Dollar' },
  { code: 'EUR', name: 'Euro' },
  { code: 'GBP', name: 'British Pound' },
  { code: 'JPY', name: 'Japanese Yen' },
  { code: 'AUD', name: 'Australian Dollar' },
  { code: 'CAD', name: 'Canadian Dollar' },
  { code: 'CHF', name: 'Swiss Franc' },
  { code: 'CNY', name: 'Chinese Yuan' },
  { code: 'IDR', name: 'Indonesian Rupiah' }
]

const timezones = [
  'UTC',
  'America/New_York',
  'America/Los_Angeles',
  'Europe/London',
  'Europe/Paris',
  'Asia/Tokyo',
  'Asia/Shanghai',
  'Asia/Jakarta',
  'Australia/Sydney'
]

const planPricing = {
  basic: { price: 29.99, features: ['Up to 5 users', 'Basic reporting', '24/7 support', 'Mobile app'] },
  premium: {
    price: 59.99,
    features: ['Up to 25 users', 'Advanced reporting', 'Priority support', 'API access', 'Custom integrations']
  },
  enterprise: {
    price: 129.99,
    features: [
      'Unlimited users',
      'Enterprise reporting',
      'Dedicated support',
      'White-label solution',
      'Custom development'
    ]
  }
}

const CreateOrganization = () => {
  const initialSelected: string = planData.filter(item => item.isSelected)[
    planData.filter(item => item.isSelected).length - 1
  ].value

  const router = useRouter()

  // States
  const [formData, setFormData] = useState<OrganizationRequest>({
    organization_name: '',
    organization_email: null,
    organization_phone_number: null,
    plan_type: initialSelected as 'basic' | 'premium' | 'enterprise',
    admin_name: '',
    admin_email: '',
    admin_password: '',
    outlet_name: '',
    outlet_address: null,
    outlet_timezone: null,
    outlet_currency: 'USD'
  })

  const [errors, setErrors] = useState<Partial<Record<keyof OrganizationRequest, string>>>({})
  const [submitError, setSubmitError] = useState<string | null>(null)

  // Hooks
  const { updatePageSettings } = useSettings()
  const { createOrganization } = useOrganizationsMutation()

  const handleInputChange = (field: keyof OrganizationRequest) => (event: ChangeEvent<HTMLInputElement>) => {
    const value = event.target.value
    setFormData(prev => ({
      ...prev,
      [field]: value || null
    }))

    // Clear error when user starts typing
    if (errors[field]) {
      setErrors(prev => ({
        ...prev,
        [field]: undefined
      }))
    }
  }

  const handlePlanChange = (prop: string | ChangeEvent<HTMLInputElement>) => {
    const planType = typeof prop === 'string' ? prop : prop.target.value
    setFormData(prev => ({
      ...prev,
      plan_type: planType as 'basic' | 'premium' | 'enterprise'
    }))
  }

  const validateForm = (): boolean => {
    const newErrors: Partial<Record<keyof OrganizationRequest, string>> = {}

    // Required fields validation
    if (!formData.organization_name.trim()) {
      newErrors.organization_name = 'Organization name is required'
    } else if (formData.organization_name.length > 255) {
      newErrors.organization_name = 'Organization name must be 255 characters or less'
    }

    if (!formData.admin_name.trim()) {
      newErrors.admin_name = 'Admin name is required'
    } else if (formData.admin_name.length > 255) {
      newErrors.admin_name = 'Admin name must be 255 characters or less'
    }

    if (!formData.admin_email.trim()) {
      newErrors.admin_email = 'Admin email is required'
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.admin_email)) {
      newErrors.admin_email = 'Please enter a valid email address'
    }

    if (!formData.admin_password) {
      newErrors.admin_password = 'Password is required'
    } else if (formData.admin_password.length < 6) {
      newErrors.admin_password = 'Password must be at least 6 characters long'
    }

    if (!formData.outlet_name.trim()) {
      newErrors.outlet_name = 'Outlet name is required'
    } else if (formData.outlet_name.length > 255) {
      newErrors.outlet_name = 'Outlet name must be 255 characters or less'
    }

    if (!formData.outlet_currency) {
      newErrors.outlet_currency = 'Currency is required'
    } else if (formData.outlet_currency.length !== 3) {
      newErrors.outlet_currency = 'Currency must be a 3-character ISO code'
    }

    // Optional email validation
    if (formData.organization_email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.organization_email)) {
      newErrors.organization_email = 'Please enter a valid email address'
    }

    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleSubmit = async () => {
    if (!validateForm()) return
    
    setSubmitError(null)

    createOrganization.mutate(formData, {
      onSuccess: () => {
        router.push('/login')
      }
    })
  }

  // For Page specific settings
  useEffect(() => {
    return updatePageSettings({
      skin: 'default'
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const selectedPlan = planPricing[formData.plan_type]

  return (
    <section className={classnames('md:plb-[100px] plb-6', frontCommonStyles.layoutSpacing)}>
      <Card>
        <Grid container>
          <Grid size={{ md: 12, lg: 8 }}>
            <CardContent className='flex flex-col max-sm:gap-y-5 gap-y-8 sm:p-8 border-be lg:border-be-0 lg:border-e bs-full'>
              <div className='flex flex-col gap-2'>
                <Typography variant='h4' className='flex items-center gap-2'>
                  <i className='tabler-building text-primary' />
                  Create Organization
                </Typography>
                <Typography>
                  Set up your organization with admin account and primary outlet. Choose the plan that best fits your
                  needs.
                </Typography>
              </div>

              {submitError && (
                <Alert severity='error' className='mb-4'>
                  {submitError}
                </Alert>
              )}

              {/* Plan Selection */}
              <div>
                <Typography variant='h5' className='mbe-4 flex items-center gap-2'>
                  <i className='tabler-crown text-warning' />
                  Choose Your Plan
                </Typography>
                <Grid container spacing={4}>
                  {planData.map((item, index) => (
                    <CustomInputHorizontal
                      key={index}
                      type='radio'
                      name='plan-type'
                      data={item}
                      selected={formData.plan_type}
                      handleChange={handlePlanChange}
                      gridProps={{ size: { xs: 12, md: 4 } }}
                    />
                  ))}
                </Grid>
              </div>

              {/* Organization Details */}
              <div>
                <Typography variant='h5' className='mbe-6 flex items-center gap-2'>
                  <i className='tabler-building text-info' />
                  Organization Details
                </Typography>
                <Grid container spacing={5}>
                  <Grid size={{ xs: 12, sm: 6 }}>
                    <CustomTextField
                      fullWidth
                      required
                      label='Organization Name'
                      placeholder='My Company Ltd.'
                      value={formData.organization_name || ''}
                      onChange={handleInputChange('organization_name')}
                      error={!!errors.organization_name}
                      helperText={errors.organization_name}
                    />
                  </Grid>
                  <Grid size={{ xs: 12, sm: 6 }}>
                    <CustomTextField
                      fullWidth
                      label='Organization Email'
                      placeholder='contact@mycompany.com'
                      type='email'
                      value={formData.organization_email || ''}
                      onChange={handleInputChange('organization_email')}
                      error={!!errors.organization_email}
                      helperText={errors.organization_email}
                    />
                  </Grid>
                  <Grid size={{ xs: 12, sm: 6 }}>
                    <CustomTextField
                      fullWidth
                      label='Phone Number'
                      placeholder='+1 (555) 123-4567'
                      value={formData.organization_phone_number || ''}
                      onChange={handleInputChange('organization_phone_number')}
                    />
                  </Grid>
                </Grid>
              </div>

              {/* Admin Account */}
              <div>
                <Typography variant='h5' className='mbe-6 flex items-center gap-2'>
                  <i className='tabler-user-shield text-success' />
                  Admin Account
                </Typography>
                <Grid container spacing={5}>
                  <Grid size={{ xs: 12, sm: 6 }}>
                    <CustomTextField
                      fullWidth
                      required
                      label='Admin Name'
                      placeholder='John Doe'
                      value={formData.admin_name || ''}
                      onChange={handleInputChange('admin_name')}
                      error={!!errors.admin_name}
                      helperText={errors.admin_name}
                    />
                  </Grid>
                  <Grid size={{ xs: 12, sm: 6 }}>
                    <CustomTextField
                      fullWidth
                      required
                      label='Admin Email'
                      placeholder='admin@mycompany.com'
                      type='email'
                      value={formData.admin_email || ''}
                      onChange={handleInputChange('admin_email')}
                      error={!!errors.admin_email}
                      helperText={errors.admin_email}
                    />
                  </Grid>
                  <Grid size={{ xs: 12, sm: 6 }}>
                    <CustomTextField
                      fullWidth
                      required
                      type='password'
                      label='Admin Password'
                      placeholder='Minimum 6 characters'
                      value={formData.admin_password || ''}
                      onChange={handleInputChange('admin_password')}
                      error={!!errors.admin_password}
                      helperText={errors.admin_password}
                    />
                  </Grid>
                </Grid>
              </div>

              {/* Outlet Information */}
              <div>
                <Typography variant='h5' className='mbe-6 flex items-center gap-2'>
                  <i className='tabler-store text-warning' />
                  Primary Outlet
                </Typography>
                <Grid container spacing={5}>
                  <Grid size={{ xs: 12, sm: 6 }}>
                    <CustomTextField
                      fullWidth
                      required
                      label='Outlet Name'
                      placeholder='Main Store'
                      value={formData.outlet_name || ''}
                      onChange={handleInputChange('outlet_name')}
                      error={!!errors.outlet_name}
                      helperText={errors.outlet_name}
                    />
                  </Grid>
                  <Grid size={{ xs: 12, sm: 6 }}>
                    <CustomTextField
                      select
                      fullWidth
                      required
                      label='Currency'
                      value={formData.outlet_currency}
                      onChange={handleInputChange('outlet_currency')}
                      error={!!errors.outlet_currency}
                      helperText={errors.outlet_currency}
                    >
                      {currencies.map(currency => (
                        <MenuItem key={currency.code} value={currency.code}>
                          {currency.code} - {currency.name}
                        </MenuItem>
                      ))}
                    </CustomTextField>
                  </Grid>
                  <Grid size={{ xs: 12 }}>
                    <CustomTextField
                      fullWidth
                      label='Outlet Address'
                      placeholder='123 Main Street, City, State, Country'
                      value={formData.outlet_address || ''}
                      onChange={handleInputChange('outlet_address')}
                    />
                  </Grid>
                  <Grid size={{ xs: 12, sm: 6 }}>
                    <CustomTextField
                      select
                      fullWidth
                      label='Timezone'
                      value={formData.outlet_timezone || ''}
                      onChange={handleInputChange('outlet_timezone')}
                    >
                      {timezones.map(tz => (
                        <MenuItem key={tz} value={tz}>
                          {tz}
                        </MenuItem>
                      ))}
                    </CustomTextField>
                  </Grid>
                </Grid>
              </div>
            </CardContent>
          </Grid>

          <Grid size={{ md: 12, lg: 4 }}>
            <CardContent className='flex flex-col gap-8 sm:p-8'>
              <div className='flex flex-col gap-2'>
                <Typography variant='h4' className='flex items-center gap-2'>
                  <i className='tabler-receipt text-primary' />
                  Plan Summary
                </Typography>
                <Typography>Review your selected plan and get started with your organization.</Typography>
              </div>

              <div className='flex flex-col gap-5'>
                <div className='flex flex-col gap-4 p-6 bg-actionHover rounded'>
                  <div className='flex items-center justify-between'>
                    <Typography className='font-medium capitalize'>{formData.plan_type} Plan</Typography>
                    <Chip
                      label={formData.plan_type === 'premium' ? 'Most Popular' : 'Selected'}
                      color={formData.plan_type === 'premium' ? 'success' : 'primary'}
                      size='small'
                    />
                  </div>
                  <div className='flex items-baseline'>
                    <Typography variant='h1'>${selectedPlan.price}</Typography>
                    <Typography component='sub'>/month</Typography>
                  </div>
                  <div className='flex flex-col gap-2'>
                    {selectedPlan.features.map((feature, index) => (
                      <div key={index} className='flex items-center gap-2'>
                        <i className='tabler-check text-success text-sm' />
                        <Typography variant='body2'>{feature}</Typography>
                      </div>
                    ))}
                  </div>
                </div>

                <div>
                  <div className='flex gap-2 items-center justify-between mbe-2'>
                    <Typography>Plan Cost</Typography>
                    <Typography color='text.primary' className='font-medium'>
                      ${selectedPlan.price}
                    </Typography>
                  </div>
                  <div className='flex gap-2 items-center justify-between'>
                    <Typography>Setup Fee</Typography>
                    <Typography color='text.primary' className='font-medium'>
                      Free
                    </Typography>
                  </div>
                  <Divider className='mlb-4' />
                  <div className='flex gap-2 items-center justify-between'>
                    <Typography className='font-medium'>Total</Typography>
                    <Typography color='text.primary' className='font-medium'>
                      ${selectedPlan.price}
                    </Typography>
                  </div>
                </div>

                <Button
                  variant='contained'
                  size='large'
                  onClick={handleSubmit}
                  disabled={createOrganization.isPending}
                  endIcon={
                    createOrganization.isPending ? (
                      <CircularProgress size={20} color='inherit' />
                    ) : (
                      <DirectionalIcon ltrIconClass='tabler-arrow-right' rtlIconClass='tabler-arrow-left' />
                    )
                  }
                >
                  {createOrganization.isPending ? 'Creating Organization...' : 'Create Organization'}
                </Button>
              </div>

              <Typography variant='body2' className='text-center'>
                By creating an organization, you agree to our Terms of Service and Privacy Policy. You can change your
                plan anytime.
              </Typography>
            </CardContent>
          </Grid>
        </Grid>
      </Card>
    </section>
  )
}

export default CreateOrganization
