import Button from '@mui/material/Button'
import Dialog from '@mui/material/Dialog'
import DialogActions from '@mui/material/DialogActions'
import DialogContent from '@mui/material/DialogContent'
import DialogTitle from '@mui/material/DialogTitle'
import FormControlLabel from '@mui/material/FormControlLabel'
import Stack from '@mui/material/Stack'
import Switch from '@mui/material/Switch'
import TextField from '@mui/material/TextField'
import { Controller, type UseFormReturn } from 'react-hook-form'
import { AddressMapPicker } from '@/features/address-map-picker'

export type AddressFormValues = {
  label: string
  recipientName: string
  recipientPhone: string
  addressLine: string
  comment: string
  lat: number | null
  lng: number | null
  isDefault: boolean
}

export function AddressFormDialog({
  open,
  onClose,
  editing,
  form,
  onSubmit,
  isPending,
}: {
  open: boolean
  onClose: () => void
  editing: boolean
  form: UseFormReturn<AddressFormValues>
  onSubmit: () => void
  isPending: boolean
}) {
  return (
    <Dialog open={open} onClose={onClose} fullWidth maxWidth="md">
      <DialogTitle>{editing ? 'Редактировать адрес' : 'Новый адрес'}</DialogTitle>
      <DialogContent>
        <Stack spacing={2} sx={{ mt: 1 }}>
          <Controller
            control={form.control}
            name="label"
            render={({ field }) => <TextField label="Метка (например: Дом/Работа)" fullWidth {...field} />}
          />
          <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
            <Controller
              control={form.control}
              name="recipientName"
              render={({ field }) => <TextField label="ФИО получателя" fullWidth required {...field} />}
            />
            <Controller
              control={form.control}
              name="recipientPhone"
              render={({ field }) => <TextField label="Телефон получателя" fullWidth required {...field} />}
            />
          </Stack>

          <Controller
            control={form.control}
            name="addressLine"
            render={({ field }) => <TextField label="Адрес" fullWidth required {...field} />}
          />
          <Controller
            control={form.control}
            name="comment"
            render={({ field }) => <TextField label="Комментарий (необязательно)" fullWidth {...field} />}
          />

          <Controller
            control={form.control}
            name="lat"
            render={({ field: latField }) => (
              <Controller
                control={form.control}
                name="lng"
                render={({ field: lngField }) => (
                  <AddressMapPicker
                    value={
                      latField.value !== null && lngField.value !== null
                        ? { lat: latField.value, lng: lngField.value }
                        : null
                    }
                    onChange={(v) => {
                      latField.onChange(v.lat)
                      lngField.onChange(v.lng)
                      if (v.addressLine) form.setValue('addressLine', v.addressLine, { shouldDirty: true })
                    }}
                  />
                )}
              />
            )}
          />

          <Controller
            control={form.control}
            name="isDefault"
            render={({ field }) => (
              <FormControlLabel
                control={<Switch checked={Boolean(field.value)} onChange={(_, v) => field.onChange(v)} />}
                label="Адрес по умолчанию"
              />
            )}
          />
        </Stack>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Отмена</Button>
        <Button
          variant="contained"
          onClick={onSubmit}
          disabled={
            isPending ||
            !form.watch('recipientName').trim() ||
            !form.watch('recipientPhone').trim() ||
            !form.watch('addressLine').trim()
          }
        >
          Сохранить
        </Button>
      </DialogActions>
    </Dialog>
  )
}
