"use client";

import Link from "next/link";
import { useCallback, useEffect, useState, type Dispatch, type ReactNode, type SetStateAction } from "react";
import { MapPicker } from "@/components/schools/MapPicker";
import { ProvinceCityFields } from "@/components/schools/ProvinceCityFields";
import { Button } from "@/components/ui/Button";
import { Field, Input, Select, Textarea } from "@/components/ui/Field";
import { ApiError, apiDelete, apiGet, apiPatch, apiPost } from "@/lib/api";
import type { BuildingDetail, BuildingSpaceRow, SpaceTypeOption } from "@/lib/buildings";

export type BuildingFormValues = {
  code: string;
  name: string;
  province: string;
  city: string;
  address: string;
  postal_code: string;
  latitude: number | null;
  longitude: number | null;
  description: string;
  is_active: boolean;
  cost_center_code: string;
};

export const emptyBuildingForm = (): BuildingFormValues => ({
  code: "",
  name: "",
  province: "",
  city: "",
  address: "",
  postal_code: "",
  latitude: null,
  longitude: null,
  description: "",
  is_active: true,
  cost_center_code: "",
});

export type BuildingFormFieldErrors = Partial<Record<keyof BuildingFormValues, string>>;

export function validateBuildingForm(value: BuildingFormValues): BuildingFormFieldErrors {
  const errors: BuildingFormFieldErrors = {};
  if (!value.name.trim()) errors.name = "نام ساختمان الزامی است.";
  if (!value.code.trim()) errors.code = "کد ساختمان الزامی است.";
  if (!value.province.trim()) errors.province = "انتخاب استان الزامی است.";
  if (!value.city.trim()) errors.city = "انتخاب شهر الزامی است.";
  if (!value.address.trim()) errors.address = "آدرس الزامی است.";
  return errors;
}

export function BuildingForm({
  value,
  onChange,
  errors = {},
  actions,
  generalError,
  buildingId,
  initialSpaces,
}: {
  value: BuildingFormValues;
  onChange: Dispatch<SetStateAction<BuildingFormValues>>;
  errors?: BuildingFormFieldErrors;
  actions?: ReactNode;
  generalError?: string | null;
  buildingId?: number;
  initialSpaces?: BuildingSpaceRow[];
}) {
  const [spaceTypes, setSpaceTypes] = useState<SpaceTypeOption[]>([]);
  const [spaces, setSpaces] = useState<BuildingSpaceRow[]>(initialSpaces ?? []);
  const [spaceError, setSpaceError] = useState<string | null>(null);
  const [spaceSaving, setSpaceSaving] = useState(false);
  const [newSpace, setNewSpace] = useState({
    name: "",
    code: "",
    type: "room",
    floor: "",
    parent_id: "",
    capacity: "",
  });

  useEffect(() => {
    apiGet<SpaceTypeOption[]>("/buildings/space-types").then(setSpaceTypes).catch(() => setSpaceTypes([]));
  }, []);

  useEffect(() => {
    if (initialSpaces) setSpaces(initialSpaces);
  }, [initialSpaces]);

  const patch = (partial: Partial<BuildingFormValues>) => onChange((prev) => ({ ...prev, ...partial }));

  const reloadSpaces = useCallback(async () => {
    if (!buildingId) return;
    try {
      const detail = await apiGet<BuildingDetail>(`/buildings/${buildingId}`);
      setSpaces(detail.spaces ?? []);
    } catch {
      /* ignore */
    }
  }, [buildingId]);

  const addSpace = async () => {
    if (!buildingId || !newSpace.name.trim()) return;
    setSpaceSaving(true);
    setSpaceError(null);
    try {
      await apiPost(`/buildings/${buildingId}/spaces`, {
        name: newSpace.name.trim(),
        code: newSpace.code.trim() || null,
        type: newSpace.type,
        floor: newSpace.floor.trim() || null,
        parent_id: newSpace.parent_id ? Number(newSpace.parent_id) : null,
        capacity: newSpace.capacity ? Number(newSpace.capacity) : null,
      });
      setNewSpace({ name: "", code: "", type: "room", floor: "", parent_id: "", capacity: "" });
      await reloadSpaces();
    } catch (err) {
      setSpaceError(err instanceof ApiError ? err.message : "خطا در ثبت بخش");
    } finally {
      setSpaceSaving(false);
    }
  };

  const toggleSpace = async (space: BuildingSpaceRow) => {
    setSpaceSaving(true);
    setSpaceError(null);
    try {
      if (space.is_active) {
        await apiDelete(`/building-spaces/${space.id}`);
      } else {
        await apiPatch(`/building-spaces/${space.id}`, { is_active: true });
      }
      await reloadSpaces();
    } catch (err) {
      setSpaceError(err instanceof ApiError ? err.message : "خطا");
    } finally {
      setSpaceSaving(false);
    }
  };

  return (
    <div className="space-y-4">
      {generalError ? <p className="text-sm text-red-600">{generalError}</p> : null}
      <div className="space-y-4 rounded-2xl border border-[var(--border)] bg-white p-4">
        <h3 className="text-base font-bold">اطلاعات ساختمان</h3>
        <div className="grid gap-3 sm:grid-cols-2">
          <Field label="نام *" error={errors.name}>
            <Input value={value.name} invalid={Boolean(errors.name)} onChange={(e) => patch({ name: e.target.value })} />
          </Field>
          <Field label="کد *" error={errors.code}>
            <Input value={value.code} invalid={Boolean(errors.code)} onChange={(e) => patch({ code: e.target.value })} />
          </Field>
        </div>
        <div className="grid gap-3 sm:grid-cols-3">
          <ProvinceCityFields
            required
            province={value.province}
            city={value.city}
            provinceError={errors.province}
            cityError={errors.city}
            onProvinceChange={(province) => patch({ province, city: "" })}
            onCityChange={(city) => patch({ city })}
          />
          <Field label="کد پستی">
            <Input value={value.postal_code} onChange={(e) => patch({ postal_code: e.target.value })} />
          </Field>
        </div>
        <Field label="آدرس *" error={errors.address}>
          <Textarea rows={3} value={value.address} invalid={Boolean(errors.address)} onChange={(e) => patch({ address: e.target.value })} />
        </Field>
        <Field label="توضیحات">
          <Textarea rows={3} value={value.description} onChange={(e) => patch({ description: e.target.value })} />
        </Field>
        <div className="grid gap-3 sm:grid-cols-2">
          <Field label="کد مرکز هزینه (مالی)">
            <Input value={value.cost_center_code} onChange={(e) => patch({ cost_center_code: e.target.value })} />
          </Field>
          <Field label="وضعیت">
            <label className="flex items-center gap-2 pt-2 text-sm">
              <input
                type="checkbox"
                checked={value.is_active}
                onChange={(e) => patch({ is_active: e.target.checked })}
              />
              فعال
            </label>
          </Field>
        </div>
        <MapPicker
          lat={value.latitude}
          lng={value.longitude}
          onChange={(lat, lng) => patch({ latitude: lat, longitude: lng })}
        />
        {actions ? <div className="flex gap-3 pt-2">{actions}</div> : null}
      </div>

      {buildingId ? (
        <div className="space-y-3 rounded-2xl border border-[var(--border)] bg-white p-4">
          <h3 className="text-base font-bold">بخش‌ها و فضاها</h3>
          <p className="text-xs text-[var(--muted)]">
            اتاق، سالن، دفتر و سایر فضاها. نوع‌ها قابل گسترش هستند و سلسله‌مراتب با «والد» پشتیبانی می‌شود.
          </p>
          {spaceError ? <p className="text-xs text-red-600">{spaceError}</p> : null}
          <div className="grid gap-2 sm:grid-cols-6">
            <Field label="نام">
              <Input value={newSpace.name} onChange={(e) => setNewSpace((s) => ({ ...s, name: e.target.value }))} />
            </Field>
            <Field label="کد">
              <Input value={newSpace.code} onChange={(e) => setNewSpace((s) => ({ ...s, code: e.target.value }))} />
            </Field>
            <Field label="نوع">
              <Select value={newSpace.type} onChange={(e) => setNewSpace((s) => ({ ...s, type: e.target.value }))}>
                {spaceTypes.map((t) => (
                  <option key={t.value} value={t.value}>
                    {t.label}
                  </option>
                ))}
              </Select>
            </Field>
            <Field label="طبقه">
              <Input value={newSpace.floor} onChange={(e) => setNewSpace((s) => ({ ...s, floor: e.target.value }))} />
            </Field>
            <Field label="والد">
              <Select
                value={newSpace.parent_id}
                onChange={(e) => setNewSpace((s) => ({ ...s, parent_id: e.target.value }))}
              >
                <option value="">—</option>
                {spaces.map((s) => (
                  <option key={s.id} value={s.id}>
                    {s.name}
                  </option>
                ))}
              </Select>
            </Field>
            <Field label="ظرفیت">
              <Input
                value={newSpace.capacity}
                onChange={(e) => setNewSpace((s) => ({ ...s, capacity: e.target.value }))}
              />
            </Field>
          </div>
          <Button loading={spaceSaving} onClick={addSpace} variant="secondary">
            افزودن بخش
          </Button>
          <ul className="divide-y divide-[var(--border)] text-sm">
            {spaces.length === 0 ? (
              <li className="py-3 text-[var(--muted)]">بخشی ثبت نشده است.</li>
            ) : (
              spaces.map((space) => (
                <li key={space.id} className="flex items-center justify-between gap-3 py-2">
                  <div>
                    <p className={space.is_active ? "font-medium" : "text-[var(--muted)] line-through"}>
                      {space.name}
                      {space.code ? <span className="mr-2 font-mono text-xs">{space.code}</span> : null}
                    </p>
                    <p className="text-xs text-[var(--muted)]">
                      {space.type_label}
                      {space.floor ? ` · طبقه ${space.floor}` : ""}
                      {space.capacity ? ` · ظرفیت ${space.capacity}` : ""}
                    </p>
                  </div>
                  <button
                    type="button"
                    className="text-xs text-teal-700 hover:underline"
                    onClick={() => toggleSpace(space)}
                  >
                    {space.is_active ? "غیرفعال" : "فعال‌سازی"}
                  </button>
                </li>
              ))
            )}
          </ul>
        </div>
      ) : (
        <p className="text-xs text-[var(--muted)]">پس از ثبت ساختمان می‌توانید بخش‌ها و فضاها را اضافه کنید.</p>
      )}

      <p className="text-xs text-[var(--muted)]">
        مدیریت لیست ساختمان‌ها در{" "}
        <Link href="/buildings" className="text-teal-700 hover:underline">
          ساختمان‌ها
        </Link>
      </p>
    </div>
  );
}
