"use client";

import { useState, useEffect, FormEvent } from "react";
import { useRouter } from "next/navigation";
import { fetchWrapper } from "@/api/fetchWrapper";
import { BASE_URL } from "@/api/config";
import Button from "@/components/ui/button/Button";
import PageBreadcrumb from "@/components/common/PageBreadCrumb";
import { toast } from "react-hot-toast";
import { use } from "react";
import Label from "@/components/form/Label";
import Input from "@/components/form/input/InputField";
import Checkbox from "@/components/form/input/Checkbox";
interface DoctorData {
  first_name: string;
  last_name: string;
  username: string;
  email: string;
  is_active: boolean;
}

// interface PageProps {
//   params: { id: string };
// }

export default function EditDoctorPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = use(params);
  const router = useRouter();
  const [formData, setFormData] = useState<DoctorData>({
    first_name: "",
    last_name: "",
    username: "",
    email: "",
    is_active: true,
  });
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchDoctor = async () => {
      try {
        const response = await fetchWrapper(`${BASE_URL}/api/users/${id}/`);
        if (!response.ok) throw new Error("خطا در دریافت اطلاعات پزشک");
        const data = await response.json();
        setFormData({
          first_name: data.first_name,
          last_name: data.last_name,
          username: data.username,
          email: data.email,
          is_active: data.is_active,
        });
      } catch (err: unknown) {
        setError(err instanceof Error ? err.message : "خطای ناشناخته");
      } finally {
        setLoading(false);
      }
    };
    fetchDoctor();
  }, [id]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleCheckboxChange = (checked: boolean) => {
    setFormData((prev) => ({
      ...prev,
      is_active: checked,
    }));
  };

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    setError(null);

    try {
      const response = await fetchWrapper(`${BASE_URL}/api/users/${id}/`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
      });
      if (response.ok) {
        toast.success("پزشک با موفقیت به‌روزرسانی شد");
        router.push("/doctors");
      } else {
        const errorData = await response.json();
        const errorMessage = Object.entries(errorData)
          .map(([k, v]) => `${k}: ${v}`)
          .join("\n");
        setError(errorMessage || "به‌روزرسانی پزشک ناموفق بود");
      }
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "خطای ناشناخته");
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) return <div>در حال بارگذاری اطلاعات پزشک...</div>;

  return (
    <>
      <PageBreadcrumb pageTitle="ویرایش پزشک" />
      <div className="rounded-sm border border-stroke bg-white shadow-default dark:border-strokedark dark:bg-boxdark">
        <div className="border-b border-stroke px-6.5 py-4 dark:border-strokedark">
          <h3 className="font-medium text-black dark:text-white">
            ویرایش اطلاعات پزشک
          </h3>
        </div>
        <form onSubmit={handleSubmit} className="p-6.5">
          {error && (
            <div className="mb-5 rounded-md bg-red-100 p-4 text-red-500">
              <pre>{error}</pre>
            </div>
          )}
          <div className="mb-4.5 grid grid-cols-1 gap-6 md:grid-cols-2">
            <div>
              <Label htmlFor="first_name">نام</Label>
              <Input type="text" name="first_name" id="first_name" placeholder="نام"
                value={formData.first_name} onChange={handleChange} required />
            </div>
            <div>
              <Label htmlFor="last_name">نام خانوادگی</Label>
              <Input type="text" name="last_name" id="last_name" placeholder="نام خانوادگی"
                value={formData.last_name} onChange={handleChange} required />
            </div>
            <div>
              <Label htmlFor="username">نام کاربری</Label>
              <Input type="text" name="username" id="username" placeholder="نام کاربری"
                value={formData.username} onChange={handleChange} required />
            </div>
            <div>
              <Label htmlFor="email">آدرس ایمیل</Label>
              <Input type="email" name="email" id="email" placeholder="آدرس ایمیل"
                value={formData.email} onChange={handleChange} />
            </div>
            <div>
              <Checkbox
                id="is_active"
                label="فعال"
                checked={formData.is_active}
                onChange={handleCheckboxChange}
              />
            </div>
          </div>
          <Button disabled={submitting}>
            {submitting ? "در حال به‌روزرسانی..." : "به‌روزرسانی پزشک"}
          </Button>
        </form>
      </div>
    </>
  );
}
