import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useAuth } from "../contexts/AuthContext";
import ProfileForm from "../components/ProfileForm";

export default function PublishProfilePage() {
  const { token } = useAuth();
  const nav = useNavigate();
  const [form, setForm] = useState({
    firstName: "",
    lastName: "",
    phone: "",
    address: "",
    description: "",
    picture: "",
    field: "",
    rate: "",
    published: true,
  });
  const [error, setError] = useState("");

  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;
    setForm((f) => ({
      ...f,
      [name]: type === "checkbox" ? checked : value,
    }));
  };

  const handleFile = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onloadend = () => setForm((f) => ({ ...f, picture: reader.result }));
    reader.readAsDataURL(file);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError("");
    // require all fields
    const {
      firstName,
      lastName,
      phone,
      address,
      description,
      picture,
      field,
      rate,
    } = form;
    if (
      !firstName ||
      !lastName ||
      !phone ||
      !address ||
      !description ||
      !picture ||
      !field ||
      rate === ""
    ) {
      return setError(
        "Please complete all fields (including picture & description) before publishing."
      );
    }

    try {
      const res = await fetch("/api/profiles", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify(form),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Publish failed");
      nav("/profile");
    } catch (err) {
      setError(err.message);
    }
  };

  return (
    <main className="form-page">
      <h1>Publish Your Seller Profile</h1>
      {error && <p className="error">{error}</p>}
      <ProfileForm
        form={form}
        handleChange={handleChange}
        handleFile={handleFile}
        editMode={true}
        user={{ role: "pro" }}
        onSubmit={handleSubmit}
        onCancel={null}
      />
    </main>
  );
}
