"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Dialog,
  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 {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { getAllDistricts } from "@/lib/bangladesh";
import { saveDeliveryFee } from "@/lib/actions/delivery-fees";

type Fee = { id: string; district: string; amount: number };

export function DeliveryFeeSettings({ fees }: { fees: Fee[] }) {
  const [rows, setRows] = useState(fees);
  const [open, setOpen] = useState(false);
  const [district, setDistrict] = useState("");
  const [amount, setAmount] = useState("");
  const [message, setMessage] = useState("");
  const [busy, setBusy] = useState(false);
  const configured = new Map(rows.map((row) => [row.district, row.amount]));

  function edit(name: string) {
    setDistrict(name);
    setAmount(configured.get(name)?.toString() ?? "");
    setMessage("");
    setOpen(true);
  }

  return (
    <Card>
      <CardHeader className="flex flex-row items-start justify-between gap-4">
        <div>
          <CardTitle>District delivery fees</CardTitle>
          <CardDescription>
            Configure the delivery fee charged for each Bangladesh district.
            Unconfigured districts use the standard shipping fallback.
          </CardDescription>
        </div>
        <Button
          onClick={() => {
            setDistrict("");
            setAmount("");
            setOpen(true);
          }}
        >
          Add fee
        </Button>
      </CardHeader>
      <CardContent>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>District</TableHead>
              <TableHead>Status</TableHead>
              <TableHead>Fee</TableHead>
              <TableHead className="text-right">Action</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {getAllDistricts().map((item) => {
              const value = configured.get(item.name);
              return (
                <TableRow key={item.id}>
                  <TableCell>{item.name}</TableCell>
                  <TableCell className="text-muted-foreground">
                    {value === undefined ? "Not configured" : "Configured"}
                  </TableCell>
                  <TableCell>
                    {value === undefined
                      ? "Uses fallback"
                      : `৳${value.toLocaleString()}`}
                  </TableCell>
                  <TableCell className="text-right">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => edit(item.name)}
                    >
                      {value === undefined ? "Configure" : "Edit"}
                    </Button>
                  </TableCell>
                </TableRow>
              );
            })}
          </TableBody>
        </Table>
      </CardContent>
      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>
              {configured.has(district) ? "Update" : "Configure"} delivery fee
            </DialogTitle>
            <DialogDescription>
              Each district can have one delivery fee. Saving an existing
              district updates its current record.
            </DialogDescription>
          </DialogHeader>
          <div className="flex flex-col gap-4">
            <div className="flex flex-col gap-2">
              <Label>District</Label>
              <Select
                items={getAllDistricts().map((item) => ({
                  value: item.name,
                  label: item.name,
                }))}
                value={district}
                onValueChange={(value) => {
                  const next = value ?? "";
                  setDistrict(next);
                  setAmount(configured.get(next)?.toString() ?? "");
                }}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select district" />
                </SelectTrigger>
                <SelectContent>
                  {getAllDistricts().map((item) => (
                    <SelectItem key={item.id} value={item.name}>
                      {item.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="flex flex-col gap-2">
              <Label htmlFor="delivery-fee">Fee (BDT)</Label>
              <Input
                id="delivery-fee"
                type="number"
                min="0"
                step="0.01"
                value={amount}
                onChange={(event) => setAmount(event.target.value)}
              />
            </div>
            {message && (
              <p className="text-sm text-destructive" role="alert">
                {message}
              </p>
            )}
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setOpen(false)}>
              Cancel
            </Button>
            <Button
              disabled={busy || !district}
              onClick={async () => {
                setBusy(true);
                const result = await saveDeliveryFee({
                  district,
                  amount: Number(amount),
                });
                if ("error" in result)
                  setMessage(result.error ?? "Could not save fee.");
                else {
                  setRows((current) =>
                    [
                      ...current.filter((row) => row.district !== district),
                      { id: district, district, amount: Number(amount) },
                    ].sort((a, b) => a.district.localeCompare(b.district)),
                  );
                  setOpen(false);
                }
                setBusy(false);
              }}
            >
              {busy ? "Saving..." : "Save fee"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </Card>
  );
}
