"use client";

import { useState } from "react";

import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { statusLabels } from "@/components/repairs/RepairStatusBadge";
import type { Repair, RepairStatus } from "@/types/repair";

type Props = {
  open: boolean;
  repair: Repair | null;
  pending: boolean;
  serverError: string;
  onOpenChange: (open: boolean) => void;
  onSubmit: (status: RepairStatus, note: string) => void;
};

const statuses: RepairStatus[] = ["new", "accepted", "diagnosis", "estimate", "waiting_for_customer", "approved", "repair", "final_test", "ready_for_pickup", "shipped", "completed", "cancelled"];

export default function RepairStatusDialog({ open, repair, pending, serverError, onOpenChange, onSubmit }: Props) {
  const [status, setStatus] = useState<RepairStatus>(repair?.status ?? "new");
  const [note, setNote] = useState("");

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Status ändern</DialogTitle>
          <DialogDescription>{repair ? `${repair.repair_number} · ${repair.customer_name}` : "Reparaturstatus aktualisieren"}</DialogDescription>
        </DialogHeader>
        <div className="grid gap-3">
          <label className="grid gap-1 text-sm">Neuer Status<select className="h-8 rounded-lg border px-2 text-sm" value={status} onChange={(event) => setStatus(event.target.value as RepairStatus)}>
            {statuses.map((item) => <option key={item} value={item}>{statusLabels[item]}</option>)}
          </select></label>
          <label className="grid gap-1 text-sm">Notiz<textarea className="min-h-24 rounded-lg border p-2 text-sm" value={note} onChange={(event) => setNote(event.target.value)} /></label>
          {serverError && <p className="text-sm text-red-600">{serverError}</p>}
        </div>
        <DialogFooter>
          <Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={pending}>Abbrechen</Button>
          <Button type="button" onClick={() => onSubmit(status, note)} disabled={pending}>{pending ? "Speichert..." : "Status speichern"}</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
