"use client";

import { useActionState, useEffect, useState } from "react";
import { DollarSign, Loader2, Trash2 } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  clearClinicPricingAction,
  setClinicPricingAction,
} from "@/lib/appwrite/clinic-pricing-actions";
import {
  initialClinicPricingActionState,
  initialClinicPricingFormState,
} from "@/lib/appwrite/clinic-pricing-types";
import { PROSTHETIC_TYPE_OPTIONS } from "@/lib/appwrite/prosthetic-types";
import type { ClinicPricing, ProstheticType } from "@/lib/appwrite/schema";

const TYPE_LABELS = Object.fromEntries(
  PROSTHETIC_TYPE_OPTIONS.map((o) => [o.value, o.label]),
) as Record<string, string>;

export function ClinicPricingDialog({
  clinicTenantId,
  clinicName,
  rows,
  defaultCurrency,
}: {
  clinicTenantId: string;
  clinicName: string;
  rows: ClinicPricing[];
  defaultCurrency: string;
}) {
  const [open, setOpen] = useState(false);

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <Button size="sm" variant="outline" onClick={() => setOpen(true)}>
        <DollarSign className="size-4" />
        Fiyatlandırma
      </Button>
      <DialogContent className="max-w-xl">
        <DialogHeader>
          <DialogTitle>{clinicName} — Fiyatlandırma</DialogTitle>
          <DialogDescription>
            Protez türü bazında özel fiyat veya yüzdelik indirim tanımlayın.
            Boş bırakırsanız katalog fiyatı uygulanır.
          </DialogDescription>
        </DialogHeader>

        <PricingForm
          clinicTenantId={clinicTenantId}
          defaultCurrency={defaultCurrency}
        />

        {rows.length > 0 && (
          <div className="space-y-2">
            <p className="text-muted-foreground text-xs font-medium uppercase tracking-wide">
              Aktif kurallar
            </p>
            <ul className="divide-y rounded-md border">
              {rows.map((r) => (
                <PricingRow key={r.$id} row={r} />
              ))}
            </ul>
          </div>
        )}

        <DialogFooter>
          <DialogClose asChild>
            <Button type="button" variant="outline">
              Kapat
            </Button>
          </DialogClose>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

function PricingForm({
  clinicTenantId,
  defaultCurrency,
}: {
  clinicTenantId: string;
  defaultCurrency: string;
}) {
  const [state, action, pending] = useActionState(
    setClinicPricingAction,
    initialClinicPricingFormState,
  );

  useEffect(() => {
    if (state.ok) toast.success("Fiyatlandırma kaydedildi.");
    else if (state.error) toast.error(state.error);
  }, [state]);

  return (
    <form action={action} className="grid gap-3 rounded-md border bg-muted/30 p-3">
      <input type="hidden" name="clinicTenantId" value={clinicTenantId} />
      <div className="grid gap-2">
        <Label htmlFor={`type-${clinicTenantId}`}>Protez Türü</Label>
        <Select name="prostheticType" required defaultValue={PROSTHETIC_TYPE_OPTIONS[0].value}>
          <SelectTrigger id={`type-${clinicTenantId}`}>
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            {PROSTHETIC_TYPE_OPTIONS.map((o) => (
              <SelectItem key={o.value} value={o.value}>
                {o.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
      <div className="grid grid-cols-3 gap-2">
        <div className="grid gap-2">
          <Label htmlFor={`custom-${clinicTenantId}`}>Özel Birim Fiyat</Label>
          <Input
            id={`custom-${clinicTenantId}`}
            name="customUnitPrice"
            type="number"
            min="0"
            step="0.01"
            placeholder="—"
          />
          {state.fieldErrors?.customUnitPrice && (
            <p className="text-destructive text-xs">{state.fieldErrors.customUnitPrice}</p>
          )}
        </div>
        <div className="grid gap-2">
          <Label htmlFor={`disc-${clinicTenantId}`}>İndirim %</Label>
          <Input
            id={`disc-${clinicTenantId}`}
            name="discountPercent"
            type="number"
            min="0"
            max="100"
            step="1"
            placeholder="—"
          />
          {state.fieldErrors?.discountPercent && (
            <p className="text-destructive text-xs">{state.fieldErrors.discountPercent}</p>
          )}
        </div>
        <div className="grid gap-2">
          <Label htmlFor={`cur-${clinicTenantId}`}>Para</Label>
          <Input
            id={`cur-${clinicTenantId}`}
            name="currency"
            defaultValue={defaultCurrency}
            maxLength={8}
            style={{ textTransform: "uppercase" }}
          />
        </div>
      </div>
      <p className="text-muted-foreground text-xs">
        Özel fiyat girilirse katalogdan bağımsız uygulanır. Sadece indirim verirseniz katalog fiyatından oran düşülür.
      </p>
      <Button type="submit" size="sm" disabled={pending}>
        {pending ? <Loader2 className="size-4 animate-spin" /> : <DollarSign className="size-4" />}
        Kaydet / Güncelle
      </Button>
    </form>
  );
}

function PricingRow({ row }: { row: ClinicPricing }) {
  const [state, action, pending] = useActionState(
    clearClinicPricingAction,
    initialClinicPricingActionState,
  );

  useEffect(() => {
    if (state.ok) toast.success("Kural silindi.");
    else if (state.error) toast.error(state.error);
  }, [state]);

  return (
    <li className="flex items-center gap-3 px-3 py-2 text-sm">
      <span className="flex-1 font-medium">
        {TYPE_LABELS[row.prostheticType] ?? row.prostheticType}
      </span>
      <span className="text-muted-foreground text-xs">
        {row.customUnitPrice !== undefined && row.customUnitPrice !== null ? (
          <>Özel fiyat: <span className="tabular-nums">{row.customUnitPrice}</span> {row.currency || "TRY"}</>
        ) : row.discountPercent ? (
          <>İndirim: %{row.discountPercent}</>
        ) : (
          "—"
        )}
      </span>
      <form action={action}>
        <input type="hidden" name="id" value={row.$id} />
        <Button type="submit" size="sm" variant="ghost" disabled={pending}>
          {pending ? <Loader2 className="size-4 animate-spin" /> : <Trash2 className="size-4" />}
        </Button>
      </form>
    </li>
  );
}

type ProstheticTypeLabel = ProstheticType;
export type { ProstheticTypeLabel };
