import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { ArrowLeft, Save } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import SectionTitle from "../../components/SectionTitle";

const API_URL = "http://localhost/backend/api/sppg/create.php";

export default function TambahSPPG() {
  const navigate = useNavigate();

  const [form, setForm] = useState({
    nama: "",
    provinsi: "",
    kabupaten: "",
    alamat: "",
    total_dana: "",
    jumlah_siswa: "",
    status: "Aktif",
  });

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const handleChange = (e) => {
    const { name, value } = e.target;

    setForm((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      setLoading(true);
      setError("");

      const res = await fetch(API_URL, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          nama: form.nama,
          provinsi: form.provinsi,
          kabupaten: form.kabupaten,
          alamat: form.alamat,
          total_dana: Number(form.total_dana) || 0,
          jumlah_siswa: Number(form.jumlah_siswa) || 0,
          status: form.status,
        }),
      });

      const result = await res.json();

      if (!result.success) {
        setError(result.message || "Gagal menambahkan data");
        return;
      }

      navigate("/admin/sppg");
    } catch (err) {
      console.error(err);
      setError("Tidak bisa terhubung ke server");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
      <Button
        variant="ghost"
        className="mb-5"
        onClick={() => navigate("/admin/sppg")}
      >
        <ArrowLeft className="w-4 h-4 mr-2" />
        Kembali
      </Button>

      <SectionTitle
        title="Tambah SPPG"
        subtitle="Tambahkan data SPPG baru ke sistem"
      />

      <div className="bg-card rounded-xl border border-border p-6 mt-6">
        {error && (
          <div className="mb-5 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-600">
            {error}
          </div>
        )}

        <form onSubmit={handleSubmit} className="space-y-5">
          <div>
            <label className="text-sm font-medium">
              Nama SPPG
            </label>
            <Input
              name="nama"
              value={form.nama}
              onChange={handleChange}
              placeholder="Contoh: SPPG Padang Utara"
              className="mt-2"
              required
            />
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
            <div>
              <label className="text-sm font-medium">
                Provinsi
              </label>
              <Input
                name="provinsi"
                value={form.provinsi}
                onChange={handleChange}
                placeholder="Contoh: Sumatera Barat"
                className="mt-2"
              />
            </div>

            <div>
              <label className="text-sm font-medium">
                Kabupaten/Kota
              </label>
              <Input
                name="kabupaten"
                value={form.kabupaten}
                onChange={handleChange}
                placeholder="Contoh: Padang"
                className="mt-2"
              />
            </div>
          </div>

          <div>
            <label className="text-sm font-medium">
              Alamat
            </label>
            <textarea
              name="alamat"
              value={form.alamat}
              onChange={handleChange}
              placeholder="Masukkan alamat lengkap"
              className="mt-2 w-full min-h-24 rounded-md border border-input bg-background px-3 py-2 text-sm"
            />
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
            <div>
              <label className="text-sm font-medium">
                Total Dana
              </label>
              <Input
                name="total_dana"
                type="number"
                value={form.total_dana}
                onChange={handleChange}
                placeholder="Contoh: 50000000"
                className="mt-2"
              />
            </div>

            <div>
              <label className="text-sm font-medium">
                Jumlah Siswa
              </label>
              <Input
                name="jumlah_siswa"
                type="number"
                value={form.jumlah_siswa}
                onChange={handleChange}
                placeholder="Contoh: 1200"
                className="mt-2"
              />
            </div>
          </div>

          <div>
            <label className="text-sm font-medium">
              Status
            </label>
            <select
              name="status"
              value={form.status}
              onChange={handleChange}
              className="mt-2 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
            >
              <option value="Aktif">Aktif</option>
              <option value="Tidak Aktif">Tidak Aktif</option>
            </select>
          </div>

          <div className="flex justify-end gap-3 pt-4">
            <Button
              type="button"
              variant="outline"
              onClick={() => navigate("/admin/sppg")}
            >
              Batal
            </Button>

            <Button
              type="submit"
              disabled={loading}
            >
              <Save className="w-4 h-4 mr-2" />
              {loading ? "Menyimpan..." : "Simpan"}
            </Button>
          </div>
        </form>
      </div>
    </div>
  );
}