package view;

import javax.swing.*;
import java.awt.*;

public class LoginView extends JPanel {
    private final JTextField identifierField = new JTextField(20);
    private final JPasswordField passwordField = new JPasswordField(20);
    private final JButton loginButton = new JButton("登 录");
    private final JButton registerButton = new JButton("还没有账号？立即注册");

    public LoginView() {
        setLayout(new GridBagLayout());

        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBorder(BorderFactory.createEmptyBorder(30, 40, 30, 40));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        JLabel titleLabel = new JLabel("欢迎回来", SwingConstants.CENTER);
        titleLabel.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 28));
        gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 2;
        formPanel.add(titleLabel, gbc);

        gbc.gridwidth = 1;
        gbc.gridx = 0; gbc.gridy = 1; addLabel(formPanel, "邮箱 / 用户名:", gbc);
        gbc.gridx = 1; gbc.gridy = 1; addComponent(formPanel, identifierField, gbc);

        gbc.gridx = 0; gbc.gridy = 2; addLabel(formPanel, "密码:", gbc);
        gbc.gridx = 1; gbc.gridy = 2; addComponent(formPanel, passwordField, gbc);

        gbc.gridx = 0; gbc.gridy = 3; gbc.gridwidth = 2;
        loginButton.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 16));
        addComponent(formPanel, loginButton, gbc);

        gbc.gridy = 4;

        registerButton.putClientProperty("FlatLaf.style", "buttonType: borderless");
        addComponent(formPanel, registerButton, gbc);

        add(formPanel);
    }

    private void addLabel(JPanel panel, String text, GridBagConstraints gbc) {
        JLabel label = new JLabel(text);
        label.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 16));
        panel.add(label, gbc);
    }

    private void addComponent(JPanel panel, JComponent comp, GridBagConstraints gbc) {
        comp.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 16));
        panel.add(comp, gbc);
    }

    public String getIdentifier() { return identifierField.getText().trim(); }
    public String getPassword() { return new String(passwordField.getPassword()); }
    public JButton getLoginButton() { return loginButton; }
    public JButton getRegisterButton() { return registerButton; }
    public void clearFields() {
        identifierField.setText("");
        passwordField.setText("");
    }
}