"use client";

import { useActionState, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Loader2, Send } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { TeethChart } from "@/components/teeth-chart";
import { Textarea } from "@/components/ui/textarea";
import { createJobAction } from "@/lib/appwrite/job-actions";
import {
  PROSTHETIC_TYPE_LABELS,
  initialJobFormState,
} from "@/lib/appwrite/job-types";
import type { JobCounterpart } from "@/lib/appwrite/job-queries";
import type { ProstheticType } from "@/lib/appwrite/schema";

const NONE_PATIENT = "__none__";

const PROSTHETIC_TYPES: ProstheticType[] = [
  "metal_porselen",
  "zirkonyum",
  "implant_ustu_zirkonyum",
  "gecici",
  "e_max",
  "diger",
];

type PatientOption = { id: string; code: string; label: string };

export function NewJobForm({
  labs,
  patients,
  defaultCurrency: _defaultCurrency,
}: {
  labs: JobCounterpart[];
  patients: PatientOption[];
  defaultCurrency: string;
}) {
  const router = useRouter();
  const [state, action, pending] = useActionState(createJobAction, initialJobFormState);
  const [patientId, setPatientId] = useState<string>(
    patients.length > 0 ? patients[0].id : NONE_PATIENT,
  );
  const [teeth, setTeeth] = useState<string[]>([]);

  const patientById = useMemo(
    () => new Map(patients.map((p) => [p.id, p])),
    [patients],
  );
  const selectedPatient = patientId !== NONE_PATIENT ? patientById.get(patientId) : undefined;

  useEffect(() => {
    if (state.ok) {
      toast.success("İş yayınlandı.");
      router.push("/jobs/outbound");
    } else if (state.error) {
      toast.error(state.error);
    }
  }, [state, router]);

  return (
    <form action={action} className="grid gap-5">
      <div className="grid gap-3 md:grid-cols-2">
        <div className="grid gap-2 md:col-span-2">
          <Label htmlFor="labTenantId">Laboratuvar *</Label>
          <Select name="labTenantId" required defaultValue={labs[0]?.tenantId}>
            <SelectTrigger id="labTenantId">
              <SelectValue placeholder="Bir laboratuvar seçin" />
            </SelectTrigger>
            <SelectContent>
              {labs.map((l) => (
                <SelectItem key={l.tenantId} value={l.tenantId}>
                  {l.companyName}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          {state.fieldErrors?.labTenantId && (
            <p className="text-destructive text-xs">{state.fieldErrors.labTenantId}</p>
          )}
        </div>

        <div className="grid gap-2 md:col-span-2">
          <div className="flex items-baseline justify-between gap-3">
            <Label htmlFor="patientId">Hasta</Label>
            <Link
              href="/patients"
              className="text-muted-foreground hover:text-foreground text-xs underline-offset-4 hover:underline"
            >
              + Yeni hasta ekle
            </Link>
          </div>
          <input
            type="hidden"
            name="patientId"
            value={patientId === NONE_PATIENT ? "" : patientId}
          />
          <Select value={patientId} onValueChange={setPatientId}>
            <SelectTrigger id="patientId">
              <SelectValue placeholder="Hasta seçin" />
            </SelectTrigger>
            <SelectContent>
              {patients.map((p) => (
                <SelectItem key={p.id} value={p.id}>
                  {p.label}{" "}
                  <span className="text-muted-foreground ml-1 font-mono text-xs">
                    {p.code}
                  </span>
                </SelectItem>
              ))}
              <SelectItem value={NONE_PATIENT}>
                Hasta listesinde yok — kodu manuel gir
              </SelectItem>
            </SelectContent>
          </Select>
          {state.fieldErrors?.patientId && (
            <p className="text-destructive text-xs">{state.fieldErrors.patientId}</p>
          )}
        </div>

        <div className="grid gap-2">
          <Label htmlFor="patientCode">
            Hasta Kodu *{" "}
            {selectedPatient && (
              <span className="text-muted-foreground text-xs">(seçili hastadan)</span>
            )}
          </Label>
          <Input
            id="patientCode"
            name="patientCode"
            required
            maxLength={50}
            placeholder="Örn. 000892"
            value={selectedPatient?.code ?? undefined}
            defaultValue={selectedPatient ? undefined : ""}
            readOnly={Boolean(selectedPatient)}
            style={{ textTransform: "uppercase" }}
            className="font-mono"
          />
          {state.fieldErrors?.patientCode && (
            <p className="text-destructive text-xs">{state.fieldErrors.patientCode}</p>
          )}
        </div>

        <div className="grid gap-2">
          <Label htmlFor="prostheticType">Protez Türü *</Label>
          <Select name="prostheticType" required>
            <SelectTrigger id="prostheticType">
              <SelectValue placeholder="Tür seçin" />
            </SelectTrigger>
            <SelectContent>
              {PROSTHETIC_TYPES.map((t) => (
                <SelectItem key={t} value={t}>
                  {PROSTHETIC_TYPE_LABELS[t]}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          {state.fieldErrors?.prostheticType && (
            <p className="text-destructive text-xs">{state.fieldErrors.prostheticType}</p>
          )}
        </div>

        <div className="grid gap-2">
          <Label htmlFor="color">Renk (Vita)</Label>
          <Input id="color" name="color" maxLength={20} placeholder="Örn. A2" />
        </div>

        <div className="grid gap-2">
          <Label htmlFor="dueDate">Termin Tarihi</Label>
          <Input id="dueDate" name="dueDate" type="date" />
        </div>

        <div className="grid gap-2 md:col-span-2">
          <Label>Diş Seçimi * <span className="text-muted-foreground text-xs">(en az 1 diş)</span></Label>
          <TeethChart value={teeth} onChange={setTeeth} />
          {state.fieldErrors?.teeth && (
            <p className="text-destructive text-xs">{state.fieldErrors.teeth}</p>
          )}
          <p className="text-muted-foreground text-xs">
            Fiyat laboratuvarın katalog ve klinik indirimine göre otomatik hesaplanır — siz girmiyorsunuz.
          </p>
        </div>

        <div className="grid gap-2 md:col-span-2">
          <Label htmlFor="description">Açıklama</Label>
          <Textarea
            id="description"
            name="description"
            rows={4}
            maxLength={2000}
            placeholder="Lab'a iletmek istediğiniz notlar — hijyenik gövde, materyal tercihi, vs."
          />
        </div>
      </div>

      <div className="flex justify-end">
        <Button type="submit" disabled={pending || labs.length === 0 || teeth.length === 0}>
          {pending ? (
            <>
              <Loader2 className="size-4 animate-spin" />
              Gönderiliyor...
            </>
          ) : (
            <>
              <Send className="size-4" />
              İşi Yayınla
            </>
          )}
        </Button>
      </div>
    </form>
  );
}
