"use client";

import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { ArrowLeft, Save, UserCog } from "lucide-react";
import { AdminBreadcrumb } from "@/components/admin/admin-breadcrumb";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { apiRequest, apiUrl, isApiRequestCanceled } from "@/lib/api";
import { getLocalizedApiMessage } from "@/lib/api-message";
import { toast } from "react-toastify";

type ApiListItem = {
  id?: number | string;
  uuid?: string;
  title?: string;
  name?: string;
};

type AdminGuide = {
  id: number | string;
  uuid: string;
  name: string;
  name_hi?: string | null;
  email: string;
  phone: string;
  alternate_phone?: string | null;
  address?: string | null;
  address_hi?: string | null;
  year_of_experience?: number | string | null;
  bio?: string | null;
  bio_hi?: string | null;
  languages?: Array<ApiListItem | string>;
  skills?: Array<ApiListItem | string>;
  locations?: Array<ApiListItem | string>;
};

type GuideDetailResponse = {
  statusCode: number;
  success: boolean;
  data?:
    | {
        guide?: AdminGuide;
      }
    | AdminGuide;
  message?: string;
  message_hi?: string;
};

type GuideOptionsResponse = {
  statusCode: number;
  success: boolean;
  data?: {
    languages?: ApiListItem[];
    skills?: ApiListItem[];
    locations?: ApiListItem[];
  };
  message?: string;
  message_hi?: string;
};

type SaveGuideResponse = {
  statusCode: number;
  success: boolean;
  data?: unknown;
  message?: string;
  message_hi?: string;
};

type ValidationErrors = Record<string, string[]>;

type GuideOptions = {
  languages: ApiListItem[];
  skills: ApiListItem[];
  locations: ApiListItem[];
};

type GuideEditForm = {
  name: string;
  name_hi: string;
  email: string;
  phone: string;
  alternate_phone: string;
  address: string;
  address_hi: string;
  year_of_experience: string;
  bio: string;
  bio_hi: string;
  language_uuids: string[];
  skill_uuids: string[];
  location_uuids: string[];
};

const emptyGuideOptions: GuideOptions = {
  languages: [],
  skills: [],
  locations: [],
};

const emptyGuideEditForm: GuideEditForm = {
  name: "",
  name_hi: "",
  email: "",
  phone: "",
  alternate_phone: "",
  address: "",
  address_hi: "",
  year_of_experience: "",
  bio: "",
  bio_hi: "",
  language_uuids: [],
  skill_uuids: [],
  location_uuids: [],
};

function getAdminToken() {
  const token = localStorage.getItem("auth_token");

  if (!token) {
    throw new Error("Admin token missing. Please login again.");
  }

  return token;
}

function getGuideFromResponse(result: GuideDetailResponse): AdminGuide | null {
  if (!result.data) return null;
  if ("guide" in result.data && !("id" in result.data)) {
    return result.data.guide || null;
  }
  return result.data as AdminGuide;
}

function getItemLabel(item: ApiListItem | string) {
  if (typeof item === "string") return item;
  return item.title || item.name || String(item.id || item.uuid || "-");
}

function getItemUuid(item: ApiListItem | string) {
  if (typeof item === "string") return item;
  return item.uuid || String(item.id || "");
}

function fieldValue(value: unknown) {
  return value === null || value === undefined ? "" : String(value);
}

function firstError(errors: ValidationErrors, field: string) {
  return errors[field]?.[0];
}

function getErrors(data: unknown) {
  if (!data || Array.isArray(data) || typeof data !== "object") {
    return {};
  }

  if ("guide" in data) {
    return {};
  }

  return data as ValidationErrors;
}

function guideToEditForm(guide: AdminGuide): GuideEditForm {
  return {
    name: fieldValue(guide.name),
    name_hi: fieldValue(guide.name_hi),
    email: fieldValue(guide.email),
    phone: fieldValue(guide.phone),
    alternate_phone: fieldValue(guide.alternate_phone),
    address: fieldValue(guide.address),
    address_hi: fieldValue(guide.address_hi),
    year_of_experience: fieldValue(guide.year_of_experience),
    bio: fieldValue(guide.bio),
    bio_hi: fieldValue(guide.bio_hi),
    language_uuids: (guide.languages || []).map(getItemUuid).filter(Boolean),
    skill_uuids: (guide.skills || []).map(getItemUuid).filter(Boolean),
    location_uuids: (guide.locations || []).map(getItemUuid).filter(Boolean),
  };
}

function EditField({
  id,
  label,
  value,
  onChange,
  error,
  type = "text",
}: {
  id: string;
  label: string;
  value: string;
  onChange: (value: string) => void;
  error?: string;
  type?: string;
}) {
  return (
    <div className="space-y-2">
      <Label htmlFor={id} className="text-sm font-bold">
        {label}
      </Label>
      <Input
        id={id}
        type={type}
        value={value}
        onChange={(event) => onChange(event.target.value)}
        className="h-11 rounded-xl border-[var(--theme-border-soft)] bg-[var(--theme-surface)]"
      />
      {error && <p className="text-xs font-semibold text-red-600">{error}</p>}
    </div>
  );
}

function EditTextarea({
  id,
  label,
  value,
  onChange,
  error,
  rows = 3,
}: {
  id: string;
  label: string;
  value: string;
  onChange: (value: string) => void;
  error?: string;
  rows?: number;
}) {
  return (
    <div className="space-y-2">
      <Label htmlFor={id} className="text-sm font-bold">
        {label}
      </Label>
      <Textarea
        id={id}
        value={value}
        onChange={(event) => onChange(event.target.value)}
        rows={rows}
        className="rounded-xl border-[var(--theme-border-soft)] bg-[var(--theme-surface)]"
      />
      {error && <p className="text-xs font-semibold text-red-600">{error}</p>}
    </div>
  );
}

function MultiSelectField({
  label,
  options,
  selected,
  onToggle,
  error,
}: {
  label: string;
  options: ApiListItem[];
  selected: string[];
  onToggle: (uuid: string) => void;
  error?: string;
}) {
  return (
    <div className="space-y-3">
      <Label className="text-sm font-bold">{label}</Label>
      <div className="grid max-h-56 gap-2 overflow-y-auto rounded-2xl border border-[var(--theme-border-soft)] bg-[var(--theme-surface)] p-3 sm:grid-cols-2">
        {options.map((option) => {
          const uuid = getItemUuid(option);
          const checked = selected.includes(uuid);

          return (
            <label
              key={uuid}
              className="flex cursor-pointer items-center gap-2 rounded-xl bg-white px-3 py-2 text-sm font-semibold"
            >
              <Checkbox
                checked={checked}
                onCheckedChange={() => onToggle(uuid)}
              />
              {getItemLabel(option)}
            </label>
          );
        })}
        {options.length === 0 && (
          <p className="text-sm text-muted-foreground">No options available.</p>
        )}
      </div>
      {error && <p className="text-xs font-semibold text-red-600">{error}</p>}
    </div>
  );
}

export default function AdminGuideEditPage() {
  const params = useParams<{ id: string }>();
  const router = useRouter();
  const guideId = Array.isArray(params.id) ? params.id[0] : params.id;
  const [guide, setGuide] = useState<AdminGuide | null>(null);
  const [form, setForm] = useState<GuideEditForm>(emptyGuideEditForm);
  const [errors, setErrors] = useState<ValidationErrors>({});
  const [options, setOptions] = useState<GuideOptions>(emptyGuideOptions);
  const [isLoading, setIsLoading] = useState(true);
  const [isOptionsLoading, setIsOptionsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState("");

  const fetchGuide = useCallback(
    async (signal?: AbortSignal) => {
      setIsLoading(true);
      setError("");

      try {
        const token = getAdminToken();
        const response = await apiRequest(apiUrl(`/admin/guides/${guideId}`), {
          method: "GET",
          headers: {
            Authorization: `Bearer ${token}`,
            Accept: "application/json",
          },
          signal,
        });
        const result = (await response.json()) as GuideDetailResponse;
        const nextGuide = getGuideFromResponse(result);

        if (!response.ok || result.success === false || !nextGuide) {
          throw new Error(
            getLocalizedApiMessage(result, "Failed to load guide details."),
          );
        }

        setGuide(nextGuide);
        setForm(guideToEditForm(nextGuide));
      } catch (fetchError) {
        if (isApiRequestCanceled(fetchError)) return;

        setGuide(null);
        setError(
          fetchError instanceof Error
            ? fetchError.message
            : "Failed to load guide details.",
        );
      } finally {
        if (!signal?.aborted) {
          setIsLoading(false);
        }
      }
    },
    [guideId],
  );

  const fetchOptions = useCallback(async (signal?: AbortSignal) => {
    setIsOptionsLoading(true);

    try {
      const response = await apiRequest(apiUrl("/guide-registration/options"), {
        method: "GET",
        headers: {
          Accept: "application/json",
        },
        signal,
      });
      const result = (await response.json()) as GuideOptionsResponse;

      if (!response.ok || result.success === false) {
        throw new Error(
          getLocalizedApiMessage(result, "Failed to load guide options."),
        );
      }

      setOptions({
        languages: result.data?.languages || [],
        skills: result.data?.skills || [],
        locations: result.data?.locations || [],
      });
    } catch (optionsError) {
      if (isApiRequestCanceled(optionsError)) return;

      setError(
        optionsError instanceof Error
          ? optionsError.message
          : "Failed to load guide options.",
      );
    } finally {
      if (!signal?.aborted) {
        setIsOptionsLoading(false);
      }
    }
  }, []);

  useEffect(() => {
    const controller = new AbortController();

    fetchGuide(controller.signal);
    fetchOptions(controller.signal);

    return () => controller.abort();
  }, [fetchGuide, fetchOptions]);

  const setField = (field: keyof GuideEditForm, value: string) => {
    setForm((current) => ({ ...current, [field]: value }));
    setErrors((current) => ({ ...current, [field]: [] }));
  };

  const toggleSelection = (
    field: "language_uuids" | "skill_uuids" | "location_uuids",
    uuid: string,
  ) => {
    setForm((current) => {
      const selected = current[field];
      const nextSelected = selected.includes(uuid)
        ? selected.filter((value) => value !== uuid)
        : [...selected, uuid];

      return { ...current, [field]: nextSelected };
    });
    setErrors((current) => ({ ...current, [field]: [] }));
  };

  const saveGuide = async () => {
    if (!guide) return;

    const guideUuid = guide.uuid || String(guide.id);
    setIsSaving(true);
    setErrors({});
    setError("");

    try {
      const token = getAdminToken();
      const response = await apiRequest(apiUrl(`/admin/guides/${guideUuid}`), {
        method: "PUT",
        headers: {
          Authorization: `Bearer ${token}`,
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          name: form.name.trim(),
          name_hi: form.name_hi,
          email: form.email.trim(),
          phone: form.phone.trim(),
          alternate_phone: form.alternate_phone,
          address: form.address,
          address_hi: form.address_hi,
          year_of_experience: form.year_of_experience,
          bio: form.bio,
          bio_hi: form.bio_hi,
          language_uuids: form.language_uuids,
          skill_uuids: form.skill_uuids,
          location_uuids: form.location_uuids,
        }),
      });
      const result = (await response.json()) as SaveGuideResponse;

      if (!response.ok || result.success === false) {
        setErrors(getErrors(result.data));
        throw new Error(
          getLocalizedApiMessage(result, "Failed to update guide."),
        );
      }

      toast.success(getLocalizedApiMessage(result, "Guide updated."));
      router.push("/admin/guides");
    } catch (saveError) {
      setError(
        saveError instanceof Error
          ? saveError.message
          : "Failed to update guide.",
      );
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <div className="space-y-6">
      <AdminBreadcrumb current="Edit Guide" />

      <Card className="overflow-hidden rounded-3xl border-[var(--theme-border-soft)] bg-white py-0 shadow-sm">
        <div className="flex flex-wrap items-center justify-between gap-4 border-b border-[var(--theme-border-soft)] px-6 py-5">
          <div className="flex items-center gap-3">
            <div className="flex h-11 w-11 items-center justify-center rounded-2xl bg-[var(--theme-primary)] text-white shadow-sm">
              <UserCog className="h-5 w-5" />
            </div>
            <div>
              <h1 className="text-2xl font-black text-foreground">
                Edit Guide
              </h1>
              <p className="text-sm text-muted-foreground">
                Update guide profile, language, expertise, and operating areas.
              </p>
            </div>
          </div>
          <Button variant="outline" className="rounded-xl" asChild>
            <Link href="/admin/guides">
              <ArrowLeft className="mr-2 h-4 w-4" />
              Back to Guides
            </Link>
          </Button>
        </div>

        <CardContent className="space-y-6 p-6">
          {error && (
            <Alert className="border-red-200 bg-red-50 text-red-700">
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

          {isLoading || isOptionsLoading ? (
            <div className="rounded-2xl border border-[var(--theme-border-soft)] p-8 text-center text-sm text-muted-foreground">
              Loading guide details...
            </div>
          ) : (
            <>
              <section className="rounded-3xl border border-[var(--theme-border-soft)] bg-white p-5 shadow-sm">
                <div className="mb-5">
                  <h2 className="text-xl font-black">Personal Information</h2>
                  <p className="text-sm text-muted-foreground">
                    Basic guide details used across the admin panel and public
                    guide profile.
                  </p>
                </div>
                <div className="grid gap-4 md:grid-cols-2">
                  <EditField
                    id="guide-edit-name"
                    label="Full Name"
                    value={form.name}
                    onChange={(value) => setField("name", value)}
                    error={firstError(errors, "name")}
                  />
                  <EditField
                    id="guide-edit-name-hi"
                    label="Full Name in Hindi"
                    value={form.name_hi}
                    onChange={(value) => setField("name_hi", value)}
                    error={firstError(errors, "name_hi")}
                  />
                  <EditField
                    id="guide-edit-email"
                    label="Email"
                    type="email"
                    value={form.email}
                    onChange={(value) => setField("email", value)}
                    error={firstError(errors, "email")}
                  />
                  <EditField
                    id="guide-edit-phone"
                    label="Phone"
                    value={form.phone}
                    onChange={(value) => setField("phone", value)}
                    error={firstError(errors, "phone")}
                  />
                  <EditField
                    id="guide-edit-alternate-phone"
                    label="Alternate Phone"
                    value={form.alternate_phone}
                    onChange={(value) => setField("alternate_phone", value)}
                    error={firstError(errors, "alternate_phone")}
                  />
                  <EditField
                    id="guide-edit-experience"
                    label="Experience (Years)"
                    type="number"
                    value={form.year_of_experience}
                    onChange={(value) => setField("year_of_experience", value)}
                    error={firstError(errors, "year_of_experience")}
                  />
                </div>
              </section>

              <section className="rounded-3xl border border-[var(--theme-border-soft)] bg-white p-5 shadow-sm">
                <div className="mb-5">
                  <h2 className="text-xl font-black">Description</h2>
                  <p className="text-sm text-muted-foreground">
                    Profile text shown for guide evaluation.
                  </p>
                </div>
                <div className="grid gap-4 md:grid-cols-2">
                  <EditTextarea
                    id="guide-edit-address"
                    label="Address"
                    value={form.address}
                    onChange={(value) => setField("address", value)}
                    error={firstError(errors, "address")}
                  />
                  <EditTextarea
                    id="guide-edit-address-hi"
                    label="Address in Hindi"
                    value={form.address_hi}
                    onChange={(value) => setField("address_hi", value)}
                    error={firstError(errors, "address_hi")}
                  />
                  <EditTextarea
                    id="guide-edit-bio"
                    label="Professional Bio"
                    value={form.bio}
                    onChange={(value) => setField("bio", value)}
                    error={firstError(errors, "bio")}
                    rows={4}
                  />
                  <EditTextarea
                    id="guide-edit-bio-hi"
                    label="Professional Bio in Hindi"
                    value={form.bio_hi}
                    onChange={(value) => setField("bio_hi", value)}
                    error={firstError(errors, "bio_hi")}
                    rows={4}
                  />
                </div>
              </section>

              <section className="rounded-3xl border border-[var(--theme-border-soft)] bg-white p-5 shadow-sm">
                <div className="mb-5">
                  <h2 className="text-xl font-black">Spoken Languages & Expertise</h2>
                  <p className="text-sm text-muted-foreground">
                    Manage the spoken languages, skills, and service locations attached to this
                    guide.
                  </p>
                </div>
                <div className="grid gap-4 lg:grid-cols-3">
                  <MultiSelectField
                    label="Spoken Languages"
                    options={options.languages}
                    selected={form.language_uuids}
                    onToggle={(uuid) => toggleSelection("language_uuids", uuid)}
                    error={
                      firstError(errors, "language_uuids") ||
                      firstError(errors, "language_uuids.0")
                    }
                  />
                  <MultiSelectField
                    label="Areas of Expertise"
                    options={options.skills}
                    selected={form.skill_uuids}
                    onToggle={(uuid) => toggleSelection("skill_uuids", uuid)}
                    error={
                      firstError(errors, "skill_uuids") ||
                      firstError(errors, "skill_uuids.0")
                    }
                  />
                  <MultiSelectField
                    label="Areas of Operation"
                    options={options.locations}
                    selected={form.location_uuids}
                    onToggle={(uuid) => toggleSelection("location_uuids", uuid)}
                    error={
                      firstError(errors, "location_uuids") ||
                      firstError(errors, "location_uuids.0")
                    }
                  />
                </div>
              </section>
            </>
          )}
        </CardContent>

        <div className="flex justify-end gap-3 border-t border-[var(--theme-border-soft)] bg-white px-6 py-4">
          <Button
            type="button"
            variant="outline"
            onClick={() => router.push("/admin/guides")}
            disabled={isSaving}
            className="rounded-xl"
          >
            Cancel
          </Button>
          <Button
            type="button"
            onClick={saveGuide}
            disabled={isSaving || isLoading || isOptionsLoading || !guide}
            className="rounded-xl bg-[var(--theme-primary)] hover:bg-[var(--theme-accent-dark)]"
          >
            <Save className="mr-2 h-4 w-4" />
            {isSaving ? "Saving..." : "Save Guide"}
          </Button>
        </div>
      </Card>
    </div>
  );
}
