using System;
using System.Drawing;
using System.Windows.Forms;
using Npgsql;
using Guna.UI2.WinForms;

namespace ProviderApp
{
    public class AddEditClientForm : Form
    {
        private int? clientId = null;
        private Guna2TextBox txtLastName, txtFirstName, txtMiddleName, txtPhone, txtAddress, txtBirthDate;
        private Guna2Button btnSave, btnCancel;
        private Label lblTitle;

        public AddEditClientForm(int? id = null)
        {
            clientId = id;
            this.Size = new Size(500, 550);
            this.StartPosition = FormStartPosition.CenterParent;
            this.BackColor = Color.FromArgb(30, 30, 30);
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;

            lblTitle = new Label()
            {
                Text = id.HasValue ? "Редактирование клиента" : "Добавление клиента",
                ForeColor = Color.White,
                Font = new Font("Segoe UI", 16F, FontStyle.Bold),
                Location = new Point(20, 20),
                AutoSize = true
            };
            this.Controls.Add(lblTitle);

            int y = 80, step = 55;

            txtLastName = AddField("Фамилия:", ref y, step);
            txtFirstName = AddField("Имя:", ref y, step);
            txtMiddleName = AddField("Отчество:", ref y, step);
            txtBirthDate = AddField("Дата рождения (ГГГГ-ММ-ДД):", ref y, step);
            txtPhone = AddField("Телефон:", ref y, step);
            txtAddress = AddField("Адрес:", ref y, step);

            btnSave = new Guna2Button()
            {
                Text = "Сохранить",
                FillColor = Color.FromArgb(230, 92, 0),
                ForeColor = Color.White,
                Location = new Point(100, y + 20),
                Size = new Size(120, 40),
                BorderRadius = 8
            };
            btnSave.Click += BtnSave_Click;
            this.Controls.Add(btnSave);

            btnCancel = new Guna2Button()
            {
                Text = "Отмена",
                FillColor = Color.FromArgb(80, 80, 80),
                ForeColor = Color.White,
                Location = new Point(240, y + 20),
                Size = new Size(120, 40),
                BorderRadius = 8
            };
            btnCancel.Click += (s, e) => this.DialogResult = DialogResult.Cancel;
            this.Controls.Add(btnCancel);

            if (id.HasValue) LoadData();
        }

        private Guna2TextBox AddField(string label, ref int y, int step)
        {
            var lbl = new Label()
            {
                Text = label,
                ForeColor = Color.FromArgb(200, 200, 200),
                Location = new Point(20, y + 10),
                Size = new Size(160, 25)
            };
            this.Controls.Add(lbl);

            var tb = new Guna2TextBox()
            {
                PlaceholderText = "Введите " + label.TrimEnd(':'),
                FillColor = Color.FromArgb(45, 45, 45),
                ForeColor = Color.White,
                BorderColor = Color.FromArgb(230, 92, 0),
                Location = new Point(190, y),
                Size = new Size(260, 40),
                BorderRadius = 8
            };
            this.Controls.Add(tb);
            y += step;
            return tb;
        }

        private void LoadData()
        {
            using (var conn = DBConnection.GetConnection())
            {
                string sql = "SELECT last_name, first_name, middle_name, phone, address, birth_date FROM clients WHERE client_id = @id";
                using (var cmd = new NpgsqlCommand(sql, conn))
                {
                    cmd.Parameters.AddWithValue("@id", clientId.Value);
                    using (var r = cmd.ExecuteReader())
                    {
                        if (r.Read())
                        {
                            txtLastName.Text = r["last_name"].ToString();
                            txtFirstName.Text = r["first_name"].ToString();
                            txtMiddleName.Text = r["middle_name"].ToString();
                            txtPhone.Text = r["phone"].ToString();
                            txtAddress.Text = r["address"].ToString();

                            // Используем DateOnly вместо DateTime
                            if (r["birth_date"] != DBNull.Value)
                            {
                                DateOnly birthDate = (DateOnly)r["birth_date"];
                                txtBirthDate.Text = birthDate.ToString("yyyy-MM-dd");
                            }
                            else
                            {
                                txtBirthDate.Text = "";
                            }
                        }
                    }
                }
            }
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtLastName.Text) || string.IsNullOrWhiteSpace(txtFirstName.Text))
            {
                MessageBox.Show("Заполните фамилию и имя.");
                return;
            }

            using (var conn = DBConnection.GetConnection())
            {
                if (clientId.HasValue)
                {
                    string sql = @"UPDATE clients SET 
                last_name=@last, first_name=@first, middle_name=@middle, 
                phone=@phone, address=@address, birth_date=@birth_date
                WHERE client_id=@id";

                    using (var cmd = new NpgsqlCommand(sql, conn))
                    {
                        cmd.Parameters.AddWithValue("@id", clientId.Value);
                        cmd.Parameters.AddWithValue("@last", txtLastName.Text);
                        cmd.Parameters.AddWithValue("@first", txtFirstName.Text);
                        cmd.Parameters.AddWithValue("@middle", txtMiddleName.Text);
                        cmd.Parameters.AddWithValue("@phone", txtPhone.Text);
                        cmd.Parameters.AddWithValue("@address", txtAddress.Text);
                        cmd.Parameters.AddWithValue("@birth_date", string.IsNullOrEmpty(txtBirthDate.Text) ? DBNull.Value : (object)DateOnly.Parse(txtBirthDate.Text));
                        cmd.ExecuteNonQuery();
                    }
                    MessageBox.Show("Клиент обновлён!");
                }
                else
                {
                    string sql = @"INSERT INTO clients (last_name, first_name, middle_name, phone, address, birth_date) 
                          VALUES (@last, @first, @middle, @phone, @address, @birth_date)
                          RETURNING client_id";

                    using (var cmd = new NpgsqlCommand(sql, conn))
                    {
                        cmd.Parameters.AddWithValue("@last", txtLastName.Text);
                        cmd.Parameters.AddWithValue("@first", txtFirstName.Text);
                        cmd.Parameters.AddWithValue("@middle", txtMiddleName.Text);
                        cmd.Parameters.AddWithValue("@phone", txtPhone.Text);
                        cmd.Parameters.AddWithValue("@address", txtAddress.Text);
                        cmd.Parameters.AddWithValue("@birth_date", string.IsNullOrEmpty(txtBirthDate.Text) ? DBNull.Value : (object)DateOnly.Parse(txtBirthDate.Text));
                        int newId = Convert.ToInt32(cmd.ExecuteScalar());
                        MessageBox.Show($"Клиент №{newId} добавлен!");
                    }
                }
            }
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
    }
}