using Register_office.Model;
using Register_office.ViewModel;

namespace Register_office.View.PatientV
{
	public partial class PatientDataForm : Form
	{
		private PatientViewModel _viewModel;

		public PatientDataForm()
		{
			Init();
		}

		public PatientDataForm(Patient e)
		{
			Init();
			SetPatientData(e);
		}

		private void Init()
		{
			InitializeComponent();
			TopMost = true;
			_viewModel = new();
			SetDataSourceToComboBoxes();
			dtpBirthday.Value =
				dtpBirthday.MaxDate = DateTime.Now;
		}

		private void SetPatientData(Patient patient)
		{
			mtbPolicy.Text = patient.PolicyNumber;
			Person p = patient.PatientNavigation;
			tbSurname.Text = p.MiddleName;
			tbName.Text = p.FirstName;
			tbPatronymic.Text = p.LastName;
			tbAddress.Text = p.Address;
			dtpBirthday.Value = new(p.BirthDate, new());
			cbGender.Text = p.Gender;

			string patientName = string.Concat(tbSurname.Text, " ",
				tbName.Text, " ", tbPatronymic.Text);

			Text = "Изменение данных";
			lblData.Dock = DockStyle.Top;
			lblData.Text = patientName;
			lblIdPerson.Text = p.PersonId.ToString();
		}

		private void SetDataSourceToComboBoxes()
		{
			cbGender.DataSource = new string[] { "Мужчина", "Женщина" };
		}

		private void TextBoxKeyPress(object sender, KeyPressEventArgs e)
		{
			// Разрешаем только буквы
			if (!char.IsControl(e.KeyChar) && !char.IsLetter(e.KeyChar))
			{
				e.Handled = true; // Блокируем ввод
			}
		}

		private void btnOK_Click(object sender, EventArgs e)
		{
			Person person = new();
			person = SetPersonData(person);
			int id = person.PersonId;

			if (lblIdPerson.Text != "")
			{
				person = _viewModel.GetPerson(id).First();
				person = SetPersonData(person);
				person.Patient.PolicyNumber = mtbPolicy.Text;
				_viewModel.Update();
			}
			else
			{
				id = _viewModel.AddPerson(person);
				if (id == -1)
				{
					DialogResult = DialogResult.None;
					return;
				}

				Patient p = new()
				{
					PatientId = id,
					PolicyNumber = mtbPolicy.Text
				};
				if (!_viewModel.AddPatient(p))
				{
					DialogResult = DialogResult.None;
					return;
				}
			}

			MessageBox.Show("Пациент успешно добавлен", "Добавление пользователя",
								MessageBoxButtons.OK, MessageBoxIcon.Information);
			Close();

		}

		private Person SetPersonData(Person p)
		{
			p.MiddleName = tbSurname.Text;
			p.FirstName = tbName.Text;
			p.LastName = tbPatronymic.Text;
			p.Address = tbAddress.Text;
			p.BirthDate = DateOnly.FromDateTime(dtpBirthday.Value);
			p.Gender = cbGender.Text;

			if (lblIdPerson.Text != "")
				p.PersonId = int.Parse(lblIdPerson.Text);

			return p;
		}
	}
}
