import React, { useState, useContext, useEffect } from "react";
import { Form, Button, Card, Container, Alert, Row, Col } from "react-bootstrap";
import { useNavigate, Link } from "react-router-dom";
import axios from "axios";
import { AuthContext } from "../../context/AuthContext";
import { FaEdit } from "react-icons/fa";
import "./Register.css";

function Register() {
  const [nama, setNama] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [konfirmasiPassword, setKonfirmasiPassword] = useState("");

  const [error, setError] = useState("");
  const [sukses, setSukses] = useState("");

  const [isLoading, setIsLoading] = useState(false);

  const [provinces, setProvinces] = useState([]);
  const [regencies, setRegencies] = useState([]);
  const [districts, setDistricts] = useState([]);

  const [selectedProvince, setSelectedProvince] = useState("");
  const [selectedRegency, setSelectedRegency] = useState("");
  const [selectedDistrict, setSelectedDistrict] = useState("");

  const [provinceName, setProvinceName] = useState("");
  const [regencyName, setRegencyName] = useState("");
  const [districtName, setDistrictName] = useState("");

  const context = useContext(AuthContext);
  const register = context.register;
  
  const navigate = useNavigate();

  useEffect(() => {
    axios
      .get("https://www.emsifa.com/api-wilayah-indonesia/api/provinces.json")
      .then((res) => setProvinces(res.data))
      .catch((err) => console.error("Gagal load provinsi", err));
  }, []);

  useEffect(() => {
    if (selectedProvince) {
      axios
        .get(
          `https://www.emsifa.com/api-wilayah-indonesia/api/regencies/${selectedProvince}.json`
        )
        .then((res) => {
          setRegencies(res.data);
          setDistricts([]);
          setSelectedRegency("");
          setSelectedDistrict("");
        })
        .catch((err) => console.error("Gagal load kota", err));
    }
  }, [selectedProvince]);

  useEffect(() => {
    if (selectedRegency) {
      axios
        .get(
          `https://www.emsifa.com/api-wilayah-indonesia/api/districts/${selectedRegency}.json`
        )
        .then((res) => {
          setDistricts(res.data);
          setSelectedDistrict("");
        })
        .catch((err) => console.error("Gagal load kecamatan", err));
    }
  }, [selectedRegency]);

  async function handleSubmit(e) {
    e.preventDefault();
    setError("");
    setSukses("");

    if (password.length < 6) {
      setError("Password harus minimal 6 karakter!");
      return;
    }

    if (password !== konfirmasiPassword) {
      setError("Password dan Konfirmasi Password tidak cocok!");
      return;
    }

    setIsLoading(true);

    let hasil = await register(nama, email, password, provinceName, regencyName, districtName);

    if (hasil.sukses) {
      setSukses("Pendaftaran berhasil! Mengarahkan ke halaman login...");
      alert(`Email konfirmasi telah dikirim ke ${email}`);
      
      setTimeout(function() {
        navigate("/login");
      }, 2000);
    } else {
      setError(hasil.pesan);
      setIsLoading(false);
    }
  }

  return (
    <div className="register-page">
      <Container className="d-flex justify-content-center align-items-center min-vh-100 py-5">
        <Card className="register-card">
          <Card.Body className="p-4">
            <div className="text-center mb-4">
              <h2 className="register-title">
                <FaEdit className="me-2" /> Daftar EduKita
              </h2>
              <p className="register-subtitle">Buat akun untuk mulai belajar</p>
            </div>

            {error && <Alert variant="danger">{error}</Alert>}
            {sukses && <Alert variant="success">{sukses}</Alert>}

            <Form onSubmit={handleSubmit}>
              <Form.Group className="mb-3" controlId="formNama">
                <Form.Label>Nama Lengkap</Form.Label>
                <Form.Control
                  type="text"
                  placeholder="Masukkan nama lengkap"
                  value={nama}
                  onChange={(e) => setNama(e.target.value)}
                  required
                />
              </Form.Group>

              <Form.Group className="mb-3" controlId="formEmail">
                <Form.Label>Email</Form.Label>
                <Form.Control
                  type="email"
                  placeholder="Masukkan email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  required
                />
              </Form.Group>

              <Form.Group className="mb-3" controlId="formPassword">
                <Form.Label>Password</Form.Label>
                <Form.Control
                  type="password"
                  placeholder="Minimal 6 karakter"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  required
                />
              </Form.Group>

              <Form.Group className="mb-4" controlId="formKonfirmasi">
                <Form.Label>Konfirmasi Password</Form.Label>
                <Form.Control
                  type="password"
                  placeholder="Ketik ulang password"
                  value={konfirmasiPassword}
                  onChange={(e) => setKonfirmasiPassword(e.target.value)}
                  required
                />
              </Form.Group>

              <Row className="mb-3">
                <Col md={12}>
                  <Form.Group className="mb-3">
                    <Form.Label>Provinsi</Form.Label>
                    <Form.Select
                      required
                      onChange={(e) => {
                        setSelectedProvince(e.target.value);
                        const p = provinces.find(item => item.id === e.target.value);
                        setProvinceName(p ? p.name : "");
                      }}
                    >
                      <option value="">Pilih Provinsi</option>
                      {provinces.map((p) => (
                        <option key={p.id} value={p.id}>
                          {p.name}
                        </option>
                      ))}
                    </Form.Select>
                  </Form.Group>
                </Col>
                <Col md={12}>
                  <Form.Group className="mb-3">
                    <Form.Label>Kota/Kabupaten</Form.Label>
                    <Form.Select
                      required
                      disabled={!selectedProvince}
                      onChange={(e) => {
                        setSelectedRegency(e.target.value);
                        const r = regencies.find(item => item.id === e.target.value);
                        setRegencyName(r ? r.name : "");
                      }}
                    >
                      <option value="">Pilih Kota</option>
                      {regencies.map((r) => (
                        <option key={r.id} value={r.id}>
                          {r.name}
                        </option>
                      ))}
                    </Form.Select>
                  </Form.Group>
                </Col>
                <Col md={12}>
                  <Form.Group className="mb-4">
                    <Form.Label>Kecamatan</Form.Label>
                    <Form.Select
                      required
                      disabled={!selectedRegency}
                      onChange={(e) => {
                        setSelectedDistrict(e.target.value);
                        const d = districts.find(item => item.id === e.target.value);
                        setDistrictName(d ? d.name : "");
                      }}
                    >
                      <option value="">Pilih Kecamatan</option>
                      {districts.map((d) => (
                        <option key={d.id} value={d.id}>
                          {d.name}
                        </option>
                      ))}
                    </Form.Select>
                  </Form.Group>
                </Col>
              </Row>

              <Button
                variant="primary"
                type="submit"
                className="w-100 btn-register mb-3"
                disabled={isLoading}
              >
                {isLoading ? "Mendaftarkan..." : "Daftar Sekarang"}
              </Button>

              <div className="text-center mt-3">
                <p className="mb-0">
                  Sudah punya akun?{" "}
                  <Link to="/login" className="login-link">
                    Masuk di sini
                  </Link>
                </p>
              </div>
            </Form>
          </Card.Body>
        </Card>
      </Container>
    </div>
  );
}

export default Register;
