import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, } from "@/components/ui/dialog";
import { Plus, Pencil, Trash2 } from "lucide-react";
const STATUS_COLORS = {
    planned: "bg-blue-100 text-blue-700 border-blue-200",
    "in-progress": "bg-yellow-100 text-yellow-700 border-yellow-200",
    completed: "bg-green-100 text-green-700 border-green-200",
    cancelled: "bg-gray-100 text-gray-500 border-gray-200",
};
const STATUS_LABELS = {
    planned: "Planned",
    "in-progress": "In Progress",
    completed: "Completed",
    cancelled: "Cancelled",
};
const COMMON_PROCEDURES = [
    "Exam & X-rays",
    "Prophylaxis (Cleaning)",
    "Composite Filling",
    "Amalgam Filling",
    "Crown (PFM)",
    "Crown (All-ceramic)",
    "Root Canal Treatment",
    "Extraction",
    "Surgical Extraction",
    "Implant Placement",
    "Implant Crown",
    "Bridge",
    "Partial Denture",
    "Full Denture",
    "Scaling & Root Planing",
    "Bleaching",
    "Veneer",
];
let nextId = 1;
const newEntry = () => ({
    id: nextId++,
    tooth: "",
    procedure: "",
    fee: 0,
    status: "planned",
    date: new Date().toISOString().substring(0, 10),
    provider: "",
    notes: "",
});
export function TreatmentPlanTab() {
    const [entries, setEntries] = useState([]);
    const [dialogOpen, setDialogOpen] = useState(false);
    const [editing, setEditing] = useState(newEntry());
    const openAdd = () => {
        setEditing(newEntry());
        setDialogOpen(true);
    };
    const openEdit = (entry) => {
        setEditing({ ...entry });
        setDialogOpen(true);
    };
    const handleSave = () => {
        setEntries((prev) => {
            const idx = prev.findIndex((e) => e.id === editing.id);
            if (idx >= 0) {
                const next = [...prev];
                next[idx] = editing;
                return next;
            }
            return [...prev, editing];
        });
        setDialogOpen(false);
    };
    const handleDelete = (id) => {
        setEntries((prev) => prev.filter((e) => e.id !== id));
    };
    const total = entries.reduce((sum, e) => sum + Number(e.fee), 0);
    const completed = entries.filter((e) => e.status === "completed").reduce((sum, e) => sum + Number(e.fee), 0);
    return (<div className="space-y-4">
      <div className="flex items-center justify-between">
        <div className="flex gap-4 text-sm text-gray-600">
          <span>Total planned: <strong>${total.toLocaleString()}</strong></span>
          <span>Completed: <strong className="text-green-600">${completed.toLocaleString()}</strong></span>
        </div>
        <Button size="sm" onClick={openAdd} className="gap-1.5">
          <Plus className="h-4 w-4"/>
          Add Treatment
        </Button>
      </div>

      <div className="border rounded-lg overflow-hidden">
        <Table>
          <TableHeader>
            <TableRow className="bg-gray-50">
              <TableHead className="w-20">Tooth</TableHead>
              <TableHead>Procedure</TableHead>
              <TableHead>Provider</TableHead>
              <TableHead className="w-24 text-right">Fee</TableHead>
              <TableHead className="w-28">Status</TableHead>
              <TableHead className="w-28">Date</TableHead>
              <TableHead className="w-20 text-right">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {entries.length === 0 ? (<TableRow>
                <TableCell colSpan={7} className="text-center text-gray-400 py-10">
                  No treatment entries yet. Click "Add Treatment" to start.
                </TableCell>
              </TableRow>) : (entries.map((entry) => (<TableRow key={entry.id}>
                  <TableCell className="font-mono text-sm">
                    {entry.tooth || "—"}
                  </TableCell>
                  <TableCell>
                    <div>
                      <p className="text-sm font-medium">{entry.procedure}</p>
                      {entry.notes && (<p className="text-xs text-gray-400 truncate max-w-xs">{entry.notes}</p>)}
                    </div>
                  </TableCell>
                  <TableCell className="text-sm text-gray-600">{entry.provider || "—"}</TableCell>
                  <TableCell className="text-right text-sm font-medium">
                    ${Number(entry.fee).toLocaleString()}
                  </TableCell>
                  <TableCell>
                    <Badge className={`text-xs border ${STATUS_COLORS[entry.status]}`} variant="outline">
                      {STATUS_LABELS[entry.status]}
                    </Badge>
                  </TableCell>
                  <TableCell className="text-sm text-gray-600">{entry.date}</TableCell>
                  <TableCell className="text-right">
                    <div className="flex justify-end gap-1">
                      <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => openEdit(entry)}>
                        <Pencil className="h-3.5 w-3.5"/>
                      </Button>
                      <Button variant="ghost" size="icon" className="h-7 w-7 text-red-500 hover:text-red-600 hover:bg-red-50" onClick={() => handleDelete(entry.id)}>
                        <Trash2 className="h-3.5 w-3.5"/>
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>)))}
          </TableBody>
        </Table>
      </div>

      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>{editing.id in (entries.map(e => e.id)) ? "Edit" : "Add"} Treatment</DialogTitle>
          </DialogHeader>
          <div className="grid grid-cols-2 gap-3 py-2">
            <div className="space-y-1">
              <Label className="text-xs">Tooth #</Label>
              <Input placeholder="e.g. 14" value={editing.tooth} onChange={(e) => setEditing((d) => ({ ...d, tooth: e.target.value }))} className="h-9 text-sm"/>
            </div>
            <div className="space-y-1">
              <Label className="text-xs">Date</Label>
              <Input type="date" value={editing.date} onChange={(e) => setEditing((d) => ({ ...d, date: e.target.value }))} className="h-9 text-sm"/>
            </div>
            <div className="col-span-2 space-y-1">
              <Label className="text-xs">Procedure</Label>
              <Select value={editing.procedure} onValueChange={(v) => setEditing((d) => ({ ...d, procedure: v }))}>
                <SelectTrigger className="h-9 text-sm">
                  <SelectValue placeholder="Select procedure..."/>
                </SelectTrigger>
                <SelectContent>
                  {COMMON_PROCEDURES.map((p) => (<SelectItem key={p} value={p}>{p}</SelectItem>))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-1">
              <Label className="text-xs">Fee ($)</Label>
              <Input type="number" min="0" value={editing.fee} onChange={(e) => setEditing((d) => ({ ...d, fee: Number(e.target.value) }))} className="h-9 text-sm"/>
            </div>
            <div className="space-y-1">
              <Label className="text-xs">Status</Label>
              <Select value={editing.status} onValueChange={(v) => setEditing((d) => ({ ...d, status: v }))}>
                <SelectTrigger className="h-9 text-sm">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {Object.keys(STATUS_LABELS).map((s) => (<SelectItem key={s} value={s}>{STATUS_LABELS[s]}</SelectItem>))}
                </SelectContent>
              </Select>
            </div>
            <div className="col-span-2 space-y-1">
              <Label className="text-xs">Provider</Label>
              <Input placeholder="Provider name" value={editing.provider} onChange={(e) => setEditing((d) => ({ ...d, provider: e.target.value }))} className="h-9 text-sm"/>
            </div>
            <div className="col-span-2 space-y-1">
              <Label className="text-xs">Notes</Label>
              <Input placeholder="Clinical notes..." value={editing.notes} onChange={(e) => setEditing((d) => ({ ...d, notes: e.target.value }))} className="h-9 text-sm"/>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDialogOpen(false)}>Cancel</Button>
            <Button onClick={handleSave} disabled={!editing.procedure}>Save</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>);
}
