import { useState } from "react";
import { Plus } from "lucide-react";
import { toast } from "sonner";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input, Textarea } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useAppStore } from "@/store";
import type { Claim } from "@/types";

interface FormState {
  patientName: string;
  providerNpi: string;
  payerName: string;
  cptCode: string;
  billedAmount: string;
  notes: string;
}

const initial: FormState = {
  patientName: "",
  providerNpi: "",
  payerName: "Blue Cross Blue Shield",
  cptCode: "99213",
  billedAmount: "",
  notes: "",
};

export function NewClaimDialog() {
  const [open, setOpen] = useState(false);
  const [form, setForm] = useState<FormState>(initial);
  const [submitting, setSubmitting] = useState(false);
  const addClaim = useAppStore((s) => s.addClaim);
  const providers = useAppStore((s) => s.providers);

  function update<K extends keyof FormState>(key: K, value: FormState[K]) {
    setForm((f) => ({ ...f, [key]: value }));
  }

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!form.patientName || !form.providerNpi || !form.billedAmount) {
      toast.error("Please fill in patient, provider, and billed amount.");
      return;
    }
    setSubmitting(true);
    const claim: Claim = {
      id: `CLM-${Math.floor(10000 + Math.random() * 89999)}`,
      patientName: form.patientName,
      providerNpi: form.providerNpi,
      payerName: form.payerName,
      cptCode: form.cptCode,
      billedAmount: Number(form.billedAmount) || 0,
      receivedAmount: 0,
      status: "submitted",
      submissionDate: new Date().toISOString(),
    };
    try {
      // The "create claim from form" path is a local-only workflow for the
      // sample-data mode. When a real backend is wired, the new claim
      // surface is the EDI file → parser → backend pipeline; there's no
      // direct `api.createClaim` endpoint. So we just push to the store
      // (and surface an error if the store update ever throws).
      addClaim(claim);
      toast.success(`Claim ${claim.id} submitted`);
      setForm(initial);
      setOpen(false);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Failed to submit claim");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button className="gap-1.5">
          <Plus className="h-4 w-4" strokeWidth={2} />
          New Claim
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-xl overflow-hidden p-0">
        <div className="px-6 pt-6 pb-2">
          <span className="eyebrow text-muted-foreground">
            New submission
          </span>
          <DialogHeader className="mt-2 space-y-1.5">
            <DialogTitle className="display text-2xl">
              Submit a new claim
            </DialogTitle>
            <DialogDescription className="text-[13px]">
              Create an 837P claim. The submission will be queued for the
              next clearinghouse cycle.
            </DialogDescription>
          </DialogHeader>
        </div>

        <form onSubmit={onSubmit} className="grid gap-5 px-6 pb-6">
          <div className="grid gap-2">
            <Label htmlFor="patientName" className="eyebrow text-muted-foreground">
              Patient
            </Label>
            <Input
              id="patientName"
              autoFocus
              placeholder="Full name"
              value={form.patientName}
              onChange={(e) => update("patientName", e.target.value)}
            />
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div className="grid gap-2">
              <Label className="eyebrow text-muted-foreground">
                Provider (NPI)
              </Label>
              <Select
                value={form.providerNpi}
                onValueChange={(v) => update("providerNpi", v)}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select provider" />
                </SelectTrigger>
                <SelectContent>
                  {providers.map((p) => (
                    <SelectItem key={p.npi} value={p.npi}>
                      <span className="mono tabular-nums">{p.npi}</span>
                      <span className="text-muted-foreground ml-2">— {p.name}</span>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="grid gap-2">
              <Label htmlFor="cptCode" className="eyebrow text-muted-foreground">
                CPT
              </Label>
              <Input
                id="cptCode"
                placeholder="99213"
                value={form.cptCode}
                onChange={(e) => update("cptCode", e.target.value)}
                className="mono tabular-nums"
              />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div className="grid gap-2">
              <Label className="eyebrow text-muted-foreground">Payer</Label>
              <Select
                value={form.payerName}
                onValueChange={(v) => update("payerName", v)}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {[
                    "Blue Cross Blue Shield",
                    "United Healthcare",
                    "Aetna",
                    "Cigna",
                    "Humana",
                    "Medicare",
                    "Medicaid TX",
                  ].map((p) => (
                    <SelectItem key={p} value={p}>
                      {p}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="grid gap-2">
              <Label htmlFor="billedAmount" className="eyebrow text-muted-foreground">
                Billed amount
              </Label>
              <Input
                id="billedAmount"
                inputMode="decimal"
                placeholder="0.00"
                value={form.billedAmount}
                onChange={(e) => update("billedAmount", e.target.value)}
                className="mono tabular-nums"
              />
            </div>
          </div>

          <div className="grid gap-2">
            <Label htmlFor="notes" className="eyebrow text-muted-foreground">
              Notes <span className="opacity-50">(optional)</span>
            </Label>
            <Textarea
              id="notes"
              placeholder="Internal notes — not transmitted to payer"
              value={form.notes}
              onChange={(e) => update("notes", e.target.value)}
              className="min-h-[80px]"
            />
          </div>

          <DialogFooter className="border-t border-border/40 -mx-6 -mb-6 mt-1 px-6 py-4 bg-background/40">
            <Button
              type="button"
              variant="ghost"
              onClick={() => setOpen(false)}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={submitting} className="gap-1.5">
              {submitting ? "Submitting…" : "Submit claim"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
