"use client";

import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { healthcareApi } from "@/src/modules/healthcare/services/healthcare-api";
import { HC } from "@/src/modules/healthcare/constants/permissions";
import { useTenantId } from "@/hooks/useTenantId";
import { useHealthcarePermissions } from "@/src/modules/healthcare/hooks/useHealthcarePermissions";
import {
  PageHeader,
  Button,
  Dialog,
  Input,
  Textarea,
  DataTable,
  EmptyState,
  LoadingState,
  ErrorState,
  Tabs,
  Timeline,
  PermissionDeniedState,
  type TimelineItem,
} from "@/src/shared/ui";
import {
  HealthcareResourceWorkspace,
  type ResourceConfig,
} from "@/src/modules/healthcare/components/crud/HealthcareResourceWorkspace";

export function MedicalRecordsResourcePage(props: { title?: string; readOnly?: boolean }) {
  const config: ResourceConfig = {
    storageKey: "medical-records",
    title: props.title ?? "پرونده پزشکی",
    viewPermission: HC.MEDICAL_RECORDS_VIEW,
    managePermission: HC.MEDICAL_RECORDS_MANAGE,
    queryKey: ["healthcare", "medical-records-list"],
    listFn: async () => [],
    createFn: (tid, body) => healthcareApi.medicalRecords.create(tid, body),
    fields: [
      { name: "clinic_id", label: "کلینیک", type: "clinic", required: true },
      { name: "patient_id", label: "بیمار", type: "patient", required: true },
      { name: "code", label: "کد", required: true },
    ],
    createLabel: "ایجاد پرونده",
  };
  return (
    <div className="space-y-6">
      <MedicalRecordLookupPanel readOnly={props.readOnly} />
      <HealthcareResourceWorkspace config={config} readOnly={props.readOnly} />
    </div>
  );
}

function MedicalRecordLookupPanel({ readOnly }: { readOnly?: boolean }) {
  const { tenantId } = useTenantId();
  const { can } = useHealthcarePermissions();
  const [recordId, setRecordId] = useState("");
  const [reason, setReason] = useState("");
  const [tab, setTab] = useState("conditions");

  const recordQ = useQuery({
    queryKey: ["healthcare", tenantId, "medical-record", recordId],
    queryFn: () => healthcareApi.medicalRecords.get(tenantId!, recordId, reason || undefined),
    enabled: !!tenantId && !!recordId,
  });

  const listsQ = useQuery({
    queryKey: ["healthcare", tenantId, "clinical-lists", recordId],
    queryFn: () => healthcareApi.medicalRecords.clinicalLists(tenantId!, recordId),
    enabled: !!tenantId && !!recordId && recordQ.isSuccess,
  });

  const qc = useQueryClient();
  const addM = useMutation({
    mutationFn: ({ kind, code, display }: { kind: string; code: string; display: string }) => {
      const body = { code, display };
      if (kind === "conditions") return healthcareApi.medicalRecords.addCondition(tenantId!, recordId, body);
      if (kind === "allergies") return healthcareApi.medicalRecords.addAllergy(tenantId!, recordId, body);
      if (kind === "medications") return healthcareApi.medicalRecords.addMedication(tenantId!, recordId, body);
      return healthcareApi.medicalRecords.addImmunization(tenantId!, recordId, body);
    },
    onSuccess: async () => {
      toast.success("افزوده شد");
      await qc.invalidateQueries({ queryKey: ["healthcare", tenantId, "clinical-lists", recordId] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const [addOpen, setAddOpen] = useState(false);
  const [addCode, setAddCode] = useState("");
  const [addDisplay, setAddDisplay] = useState("");

  if (!tenantId) return null;
  if (!can(HC.MEDICAL_RECORDS_VIEW)) return <PermissionDeniedState />;

  const listForTab = () => {
    const d = listsQ.data;
    if (!d) return [];
    if (tab === "conditions") return d.conditions;
    if (tab === "allergies") return d.allergies;
    if (tab === "medications") return d.medications;
    return d.immunizations;
  };

  return (
    <section className="rounded-2xl border border-[var(--border)] bg-[var(--surface)] p-5">
      <PageHeader title="جستجوی پرونده" description="با شناسه پرونده و دلیل دسترسی (audit)." />
      <div className="flex flex-wrap gap-2">
        <Input value={recordId} onChange={(e) => setRecordId(e.target.value)} placeholder="Medical Record ID" className="max-w-xs" />
        <Input value={reason} onChange={(e) => setReason(e.target.value)} placeholder="دلیل دسترسی (اختیاری)" className="max-w-xs" />
        <Button type="button" variant="outline" onClick={() => recordQ.refetch()} disabled={!recordId}>
          بارگذاری
        </Button>
      </div>
      {recordQ.isLoading ? <LoadingState /> : null}
      {recordQ.error ? <ErrorState message={recordQ.error.message} /> : null}
      {recordQ.data ? (
        <div className="mt-4 space-y-4">
          <p className="text-sm text-secondary">
            پرونده <strong>{recordQ.data.code}</strong> — نسخه {recordQ.data.version}
          </p>
          <Tabs
            items={[
              { id: "conditions", label: "بیماری‌ها" },
              { id: "allergies", label: "آلرژی" },
              { id: "medications", label: "داروها" },
              { id: "immunizations", label: "واکسن" },
            ]}
            value={tab}
            onChange={setTab}
          />
          {!readOnly && can(HC.MEDICAL_RECORDS_MANAGE) ? (
            <Button type="button" size="sm" onClick={() => setAddOpen(true)}>
              افزودن مورد
            </Button>
          ) : null}
          <DataTable
            columns={[
              { key: "code", header: "کد" },
              { key: "display", header: "عنوان", render: (r) => String(r.display ?? r.substance ?? r.vaccine_code ?? "—") },
            ]}
            rows={listForTab() as unknown as Record<string, unknown>[]}
            empty={<EmptyState title="موردی ثبت نشده" />}
          />
        </div>
      ) : null}

      <Dialog open={addOpen} onClose={() => setAddOpen(false)} title="افزودن به لیست بالینی" size="sm">
        <div className="space-y-3">
          <Input value={addCode} onChange={(e) => setAddCode(e.target.value)} placeholder="کد" />
          <Textarea value={addDisplay} onChange={(e) => setAddDisplay(e.target.value)} placeholder="عنوان / توضیح" rows={2} />
        </div>
        <div className="mt-4 flex justify-end gap-2">
          <Button type="button" variant="outline" onClick={() => setAddOpen(false)}>انصراف</Button>
          <Button
            type="button"
            disabled={!addCode || addM.isPending}
            onClick={() => addM.mutate({ kind: tab, code: addCode, display: addDisplay })}
          >
            ثبت
          </Button>
        </div>
      </Dialog>
    </section>
  );
}

export function EncountersResourcePage(props: { title?: string; readOnly?: boolean }) {
  const [recordId, setRecordId] = useState("");
  const { tenantId } = useTenantId();
  const qc = useQueryClient();

  const createM = useMutation({
    mutationFn: (body: Record<string, unknown>) => healthcareApi.encounters.create(tenantId!, body),
    onSuccess: () => {
      toast.success("Encounter ایجاد شد");
      qc.invalidateQueries({ queryKey: ["healthcare", "encounters"] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  return (
    <div className="space-y-4">
      <PageHeader title={props.title ?? "Encounter / ویزیت بالینی"} description="ایجاد و نهایی‌سازی encounter." />
      {!props.readOnly ? (
        <div className="grid gap-3 rounded-2xl border border-[var(--border)] p-4 sm:grid-cols-2">
          <Input value={recordId} onChange={(e) => setRecordId(e.target.value)} placeholder="Medical Record ID" />
          <Button
            type="button"
            onClick={() =>
              createM.mutate({
                medical_record_id: recordId,
                doctor_id: "",
                code: `ENC-${Date.now()}`,
                chief_complaint: "—",
              })
            }
            disabled={!recordId || createM.isPending}
          >
            Encounter جدید (نیاز به doctor_id در فرم کامل)
          </Button>
        </div>
      ) : null}
      <EncountersWorkspace readOnly={props.readOnly} />
    </div>
  );
}

function EncountersWorkspace({ readOnly }: { readOnly?: boolean }) {
  const config: ResourceConfig = {
    storageKey: "encounters",
    title: "Encounterها",
    viewPermission: HC.ENCOUNTERS_MANAGE,
    queryKey: ["healthcare", "encounters"],
    listFn: async () => [],
    fields: [
      { name: "code", label: "کد" },
      { name: "status", label: "وضعیت" },
      { name: "chief_complaint", label: "شکایت اصلی" },
      { name: "clinical_summary", label: "خلاصه", type: "textarea" },
    ],
  };
  return <HealthcareResourceWorkspace config={config} readOnly={readOnly} />;
}

export function SettingsResourcePage(props: { title?: string; description?: string }) {
  const { tenantId } = useTenantId();
  const { canManage } = useHealthcarePermissions();
  const qc = useQueryClient();
  const [upsertOpen, setUpsertOpen] = useState(false);
  const [key, setKey] = useState("");
  const [valueJson, setValueJson] = useState("{}");
  const [description, setDescription] = useState("");

  const listQ = useQuery({
    queryKey: ["healthcare", tenantId, "settings"],
    queryFn: () => healthcareApi.settings.list(tenantId!),
    enabled: !!tenantId,
  });

  const upsertM = useMutation({
    mutationFn: () =>
      healthcareApi.settings.upsert(tenantId!, {
        key,
        value: JSON.parse(valueJson || "{}"),
        description: description || undefined,
      }),
    onSuccess: async () => {
      toast.success("ذخیره شد");
      setUpsertOpen(false);
      await qc.invalidateQueries({ queryKey: ["healthcare", tenantId, "settings"] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  if (!tenantId || listQ.isLoading) return <LoadingState />;
  if (listQ.error) return <ErrorState message={listQ.error.message} onRetry={() => listQ.refetch()} />;

  return (
    <div>
      <PageHeader
        title={props.title ?? "تنظیمات"}
        description={props.description ?? "settings API — upsert پشتیبانی می‌شود."}
        actions={
          canManage(HC.SETTINGS_VIEW, HC.SETTINGS_MANAGE) ? (
            <Button type="button" onClick={() => setUpsertOpen(true)}>تنظیم جدید</Button>
          ) : null
        }
      />
      <DataTable
        columns={[
          { key: "key", header: "کلید" },
          { key: "value", header: "مقدار", render: (r) => <code className="text-xs">{JSON.stringify(r.value)}</code> },
          { key: "description", header: "توضیح", render: (r) => String(r.description ?? "—") },
        ]}
        rows={(listQ.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="تنظیماتی ثبت نشده" />}
      />
      <Dialog open={upsertOpen} onClose={() => setUpsertOpen(false)} title="Upsert تنظیم" size="md">
        <div className="space-y-3">
          <Input value={key} onChange={(e) => setKey(e.target.value)} placeholder="key" />
          <Textarea value={valueJson} onChange={(e) => setValueJson(e.target.value)} placeholder='{"enabled":true}' rows={4} />
          <Input value={description} onChange={(e) => setDescription(e.target.value)} placeholder="توضیح" />
        </div>
        <div className="mt-4 flex justify-end gap-2">
          <Button type="button" variant="outline" onClick={() => setUpsertOpen(false)}>انصراف</Button>
          <Button type="button" onClick={() => upsertM.mutate()} disabled={!key || upsertM.isPending}>ذخیره</Button>
        </div>
      </Dialog>
    </div>
  );
}

export function PermissionsCatalogPage() {
  const { tenantId } = useTenantId();
  const permQ = useQuery({
    queryKey: ["healthcare", tenantId, "permissions"],
    queryFn: () => healthcareApi.permissions.catalog(tenantId!),
    enabled: !!tenantId,
  });

  if (!tenantId || permQ.isLoading) return <LoadingState />;
  if (permQ.error) return <ErrorState message={permQ.error.message} onRetry={() => permQ.refetch()} />;

  return (
    <div>
      <PageHeader
        title="کاتالوگ دسترسی‌ها"
        description={`${permQ.data?.count ?? 0} permission — ${permQ.data?.prefix}`}
      />
      <DataTable
        columns={[{ key: "permission", header: "Permission" }]}
        rows={(permQ.data?.permissions ?? []).map((p) => ({ permission: p }))}
        empty={<EmptyState title="دسترسی‌ای تعریف نشده" />}
      />
    </div>
  );
}

export function AuditExplorerPage(props: { entityType?: string; entityId?: string; title?: string }) {
  const { tenantId } = useTenantId();
  const [entityType, setEntityType] = useState(props.entityType ?? "clinic");
  const [entityId, setEntityId] = useState(props.entityId ?? "");

  const logsQ = useQuery({
    queryKey: ["healthcare", tenantId, "audit-explorer", entityType, entityId],
    queryFn: () => healthcareApi.audit.list(tenantId!, entityType, entityId),
    enabled: !!tenantId && !!entityId,
  });

  const timeline: TimelineItem[] = (logsQ.data ?? []).map((log) => ({
    id: log.id,
    title: log.action,
    subtitle: log.message ?? undefined,
    timestamp: log.created_at,
  }));

  return (
    <div>
      <PageHeader title={props.title ?? "لاگ و Audit"} description="تاریخچه فعالیت موجودیت." />
      <div className="mb-4 flex flex-wrap gap-2">
        <Input value={entityType} onChange={(e) => setEntityType(e.target.value)} placeholder="entity_type" className="max-w-[160px]" />
        <Input value={entityId} onChange={(e) => setEntityId(e.target.value)} placeholder="entity_id" className="max-w-xs" />
        <Button type="button" variant="outline" onClick={() => logsQ.refetch()} disabled={!entityId}>
          نمایش
        </Button>
      </div>
      {logsQ.isLoading ? <LoadingState /> : <Timeline items={timeline} />}
    </div>
  );
}
