"use client";

import { use, useState } from "react";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm, type Resolver } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";
import { Eye, Pencil, ShieldCheck, ShieldOff } from "lucide-react";
import { PageHeader, Breadcrumbs } from "@/components/shared/page-header";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/input";
import { FormField } from "@/components/ui/form-field";
import { Skeleton } from "@/components/ui/skeleton";
import { ErrorState } from "@/components/shared/states";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { EmploymentBadge, DriverStatusBadge } from "@/components/shared/status-badges";
import { useI18n, useT } from "@/i18n";
import { useDriver } from "@/features/captains/use-driver";
import { EditCaptainDialog } from "@/features/captains/edit-captain-dialog";
import {
  approveDriver,
  rejectDriver,
  requestDriverDocuments,
  toggleDriverActivation,
  type VehicleAssignmentInput,
} from "@/services/drivers";
import { useCan } from "@/features/auth/use-can";
import { applyFieldErrors, friendlyErrorMessage } from "@/lib/errors";
import { formatDate, formatDateTime } from "@/lib/format";

const reviewNoteSchema = z.object({
  review_note: z.string().min(1, "errors.required"),
});

const vehicleSchema = z.object({
  plate_number: z.string().min(1, "errors.required"),
  brand: z.string().min(1, "errors.required"),
  model: z.string().min(1, "errors.required"),
  manufacture_year: z.coerce
    .number()
    .int()
    .min(1900, "errors.generic")
    .max(new Date().getFullYear() + 1, "errors.generic"),
  color: z.string().min(1, "errors.required"),
});

type ReviewNoteValues = z.infer<typeof reviewNoteSchema>;
type VehicleValues = z.infer<typeof vehicleSchema>;

// `z.coerce.number()` widens the schema input type to `unknown`; zodResolver is
// given a `Resolver` whose input matches the form's already-coerced values.
const vehicleResolver = zodResolver(vehicleSchema) as unknown as Resolver<VehicleValues>;

type DialogKind = "approve" | "reject" | "documents";

export default function CaptainDetailPage({
  params,
}: {
  params: Promise<{ ulid: string }>;
}) {
  const t = useT();
  const { locale } = useI18n();
  const { can } = useCan();
  const { ulid } = use(params);

  const { data, isLoading, isError, error, refetch } = useDriver(ulid);
  const driver = data?.Model ?? null;

  const [dialog, setDialog] = useState<DialogKind | null>(null);
  const [editOpen, setEditOpen] = useState(false);
  const [busy, setBusy] = useState(false);

  const noteForm = useForm<ReviewNoteValues>({
    resolver: zodResolver(reviewNoteSchema),
    mode: "onTouched",
    defaultValues: { review_note: "" },
  });

  const vehicleForm = useForm<VehicleValues>({
    resolver: vehicleResolver,
    mode: "onTouched",
    defaultValues: {
      plate_number: "",
      brand: "",
      model: "",
      manufacture_year: new Date().getFullYear(),
      color: "",
    },
  });

  function closeDialog() {
    setDialog(null);
    noteForm.reset();
    vehicleForm.reset();
  }

  async function runAction(
    action: () => Promise<unknown>,
  ) {
    setBusy(true);
    try {
      const response = (await action()) as { Message: string | null };
      toast.success(response.Message || t("applications.approve"));
      closeDialog();
      await refetch();
    } catch (caught) {
      // Two forms feed one request, so each takes only what it renders: the note box, and the
      // vehicle fields the server names `vehicle.*` — a plate already held by another captain is
      // the refusal that actually happens here.
      const onNote = applyFieldErrors(
        caught,
        (field, message) => noteForm.setError(field as never, { message }),
        { only: ["review_note"] },
      );
      const onVehicle = applyFieldErrors(
        caught,
        (field, message) => vehicleForm.setError(field as never, { message }),
        { prefix: "vehicle" },
      );
      if (onNote + onVehicle === 0) toast.error(friendlyErrorMessage(caught, t));
    } finally {
      setBusy(false);
    }
  }

  async function handleApprove() {
    if (!driver) return;
    if (driver.vehicle?.ownership_type === "company_owned") {
      const valid = await vehicleForm.trigger();
      if (!valid) return;
      const values = vehicleForm.getValues();
      const vehicle: VehicleAssignmentInput = {
        plate_number: values.plate_number,
        brand: values.brand,
        model: values.model,
        manufacture_year: values.manufacture_year,
        color: values.color,
      };
      await runAction(() => approveDriver(ulid, vehicle));
      return;
    }
    await runAction(() => approveDriver(ulid));
  }

  async function handleReject() {
    const valid = await noteForm.trigger();
    if (!valid) return;
    const data = noteForm.getValues();
    await runAction(() => rejectDriver(ulid, data.review_note));
  }

  async function handleRequestDocuments() {
    const valid = await noteForm.trigger();
    if (!valid) return;
    const data = noteForm.getValues();
    await runAction(() => requestDriverDocuments(ulid, data.review_note));
  }

  async function handleToggleActivation() {
    if (!driver) return;
    await runAction(() => toggleDriverActivation(ulid));
  }

  const canReview = can("drivers.review");
  const canUpdate = can("drivers.update");

  if (isLoading) {
    return (
      <div className="mx-auto max-w-5xl space-y-4">
        <Skeleton className="h-8 w-72" />
        <Skeleton className="h-48 w-full" />
        <Skeleton className="h-64 w-full" />
      </div>
    );
  }

  if (isError || !driver) {
    return (
      <div className="mx-auto max-w-2xl py-10">
        <ErrorState
          message={friendlyErrorMessage(error ?? new Error(t("common.notFound")), t)}
          onRetry={() => refetch()}
        />
      </div>
    );
  }

  const needsFleetVehicle =
    driver.vehicle?.ownership_type === "company_owned" && driver.status === "pending";

  return (
    <div className="mx-auto max-w-5xl">
      <Breadcrumbs
        items={[
          { label: t("nav.captains"), href: "/captains" },
          { label: driver.name },
        ]}
      />
      <PageHeader
        title={driver.name}
        subtitle={
          <span className="flex flex-wrap items-center gap-2 text-sm">
            <DriverStatusBadge status={driver.status} label={driver.status_label} />
            <EmploymentBadge type={driver.employment_type} label={driver.employment_type_label} />
            {!driver.is_active ? (
              <span className="rounded-md border border-input bg-surface px-2 py-0.5 text-xs font-medium text-muted-foreground">
                {t("common.inactive")}
              </span>
            ) : null}
          </span>
        }
        actions={
          <>
            {canReview && (driver.status === "pending" || driver.status === "documents_required") ? (
              <>
                <Button variant="outline" onClick={() => setDialog("reject")}>
                  {t("applications.reject")}
                </Button>
                <Button variant="outline" onClick={() => setDialog("documents")}>
                  {t("applications.requestDocuments")}
                </Button>
                <Button onClick={() => setDialog("approve")}>{t("applications.approve")}</Button>
              </>
            ) : null}
            {canUpdate ? (
              <Button variant="outline" onClick={() => setEditOpen(true)}>
                <Pencil className="h-4 w-4" aria-hidden />
                {t("common.edit")}
              </Button>
            ) : null}
            {canUpdate ? (
              <Button variant="outline" onClick={handleToggleActivation} loading={busy}>
                {driver.is_active ? (
                  <ShieldOff className="h-4 w-4" aria-hidden />
                ) : (
                  <ShieldCheck className="h-4 w-4" aria-hidden />
                )}
                {driver.is_active ? t("drivers.deactivate") : t("drivers.activate")}
              </Button>
            ) : null}
          </>
        }
      />

      <div className="grid gap-6 lg:grid-cols-3">
        <Card>
          <CardHeader>
            <CardTitle>{t("drivers.detailSections.identity")}</CardTitle>
          </CardHeader>
          <CardContent className="grid gap-3 text-sm">
            <InfoRow label={t("drivers.fieldName")} value={driver.name} />
            <InfoRow label={t("drivers.fieldPhone")} value={driver.phone} ltr />
            <InfoRow label={t("drivers.fieldEmail")} value={driver.email ?? "—"} ltr />
            <InfoRow label={t("drivers.fieldNationalId")} value={driver.national_id ?? "—"} ltr />
            <InfoRow label={t("drivers.fieldDateOfBirth")} value={formatDate(driver.date_of_birth, locale)} />
            <InfoRow label={t("common.createdAt")} value={formatDateTime(driver.created_at, locale)} />
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>{t("drivers.detailSections.documents")}</CardTitle>
          </CardHeader>
          <CardContent className="grid gap-3 text-sm">
            <PhotoRow label={t("drivers.fieldDrivingLicensePhoto")} src={driver.documents?.driving_license} />
            <PhotoRow label={t("drivers.fieldProfilePhoto")} src={driver.documents?.profile_photo} />
            <InfoRow label={t("drivers.fieldDrivingLicenseNumber")} value={driver.driving_license_number ?? "—"} ltr />
            <InfoRow
              label={t("drivers.fieldDrivingLicenseExpires")}
              value={formatDate(driver.driving_license_expires_at, locale)}
            />
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>{t("drivers.detailSections.vehicle")}</CardTitle>
          </CardHeader>
          <CardContent className="grid gap-3 text-sm">
            {driver.vehicle ? (
              <>
                <InfoRow label={t("applications.vehicleAssignment")} value={driver.vehicle.brand ?? "—"} />
                <InfoRow label="Model" value={driver.vehicle.model ?? "—"} />
                <InfoRow label="Year" value={driver.vehicle.manufacture_year ? String(driver.vehicle.manufacture_year) : "—"} />
                <InfoRow label="Color" value={driver.vehicle.color ?? "—"} />
                <InfoRow label="Plate" value={driver.vehicle.plate_number ?? "—"} ltr />
              </>
            ) : (
              <p className="text-xs text-muted-foreground">{t("common.notAvailable")}</p>
            )}
            {driver.review_note ? (
              <InfoRow label={t("drivers.fieldReviewNote")} value={driver.review_note} />
            ) : null}
          </CardContent>
        </Card>
      </div>

      <EditCaptainDialog driver={driver} open={editOpen} onOpenChange={setEditOpen} />

      <Dialog open={dialog !== null} onOpenChange={(open) => !open && closeDialog()}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>
              {dialog === "approve"
                ? t("applications.approveTitle")
                : dialog === "reject"
                  ? t("applications.rejectTitle")
                  : t("applications.documentsTitle")}
            </DialogTitle>
            <DialogDescription>
              {dialog === "approve"
                ? t("applications.approveBody")
                : dialog === "reject"
                  ? t("applications.rejectBody")
                  : t("applications.documentsBody")}
            </DialogDescription>
          </DialogHeader>

          {dialog === "approve" && needsFleetVehicle ? (
            <>
              <div className="rounded-lg border p-4 text-xs leading-relaxed text-muted-foreground">
                {t("applications.vehicleHint")}
              </div>
              <div className="grid gap-3">
                <FormField
                  label="Plate number"
                  htmlFor="plate_number"
                  required
                  error={vehicleForm.formState.errors.plate_number?.message}
                >
                  <Input id="plate_number" dir="ltr" placeholder="ABC 1234" {...vehicleForm.register("plate_number")} />
                </FormField>
                <div className="grid grid-cols-2 gap-3">
                  <FormField label="Brand" htmlFor="brand" required error={vehicleForm.formState.errors.brand?.message}>
                    <Input id="brand" {...vehicleForm.register("brand")} />
                  </FormField>
                  <FormField label="Model" htmlFor="model" required error={vehicleForm.formState.errors.model?.message}>
                    <Input id="model" {...vehicleForm.register("model")} />
                  </FormField>
                  <FormField
                    label="Year"
                    htmlFor="manufacture_year"
                    required
                    error={vehicleForm.formState.errors.manufacture_year?.message}
                  >
                    <Input
                      id="manufacture_year"
                      type="number"
                      min={1900}
                      dir="ltr"
                      {...vehicleForm.register("manufacture_year", { valueAsNumber: true })}
                    />
                  </FormField>
                  <FormField label="Color" htmlFor="color" required error={vehicleForm.formState.errors.color?.message}>
                    <Input id="color" {...vehicleForm.register("color")} />
                  </FormField>
                </div>
              </div>
            </>
          ) : null}

          {dialog === "reject" || dialog === "documents" ? (
            <FormField
              label={
                dialog === "reject"
                  ? t("applications.reasonForReject")
                  : t("applications.whatIsMissing")
              }
              htmlFor="review_note"
              required
              error={noteForm.formState.errors.review_note?.message}
            >
              <Textarea
                id="review_note"
                rows={3}
                placeholder={t("applications.reviewNotePlaceholder")}
                {...noteForm.register("review_note")}
              />
            </FormField>
          ) : null}

          <DialogFooter>
            <Button variant="outline" onClick={closeDialog} disabled={busy}>
              {t("common.cancel")}
            </Button>
            <Button
              variant={dialog === "reject" ? "destructive" : "default"}
              loading={busy}
              onClick={
                dialog === "approve"
                  ? handleApprove
                  : dialog === "reject"
                    ? handleReject
                    : handleRequestDocuments
              }
            >
              {dialog === "approve"
                ? t("applications.approve")
                : dialog === "reject"
                  ? t("applications.reject")
                  : t("applications.requestDocuments")}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

function InfoRow({ label, value, ltr = false }: { label: string; value: string; ltr?: boolean }) {
  return (
    <div>
      <dt className="text-xs font-medium text-muted-foreground">{label}</dt>
      <dd
        className="font-medium text-foreground"
        dir={ltr ? "ltr" : undefined}
        style={ltr ? { textAlign: "start" } : undefined}
      >
        {value}
      </dd>
    </div>
  );
}

function PhotoRow({ label, src }: { label: string; src?: string | null }) {
  const [expanded, setExpanded] = useState(false);
  return (
    <div>
      <dt className="mb-1 text-xs font-medium text-muted-foreground">{label}</dt>
      <dd>
        {src ? (
          <>
            <button
              type="button"
              onClick={() => setExpanded(true)}
              className="group flex items-center gap-2 rounded-lg border p-2 transition-colors hover:border-primary/30"
            >
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src={src} alt={label} className="h-12 w-12 rounded-md object-cover" />
              <span className="inline-flex items-center gap-1.5 text-xs font-medium text-primary">
                <Eye className="h-3.5 w-3.5" aria-hidden />
                {label}
              </span>
            </button>
            <Dialog open={expanded} onOpenChange={(open) => !open && setExpanded(false)}>
              <DialogContent className="max-w-2xl">
                <DialogHeader>
                  <DialogTitle>{label}</DialogTitle>
                </DialogHeader>
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img src={src} alt={label} className="mx-auto max-h-[70vh] rounded-lg object-contain" />
              </DialogContent>
            </Dialog>
          </>
        ) : (
          <span className="text-xs text-muted-foreground">—</span>
        )}
      </dd>
    </div>
  );
}