import { useState } from "react";
import { Download, Loader2 } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { cn } from "@/lib/utils";
import type { Transaksi } from "@/lib/keuangan";
import {
  exportTransaksiXlsx,
  saringPeriode,
  type ModePeriode,
  type OpsiExport,
} from "@/lib/export-excel";

const MODE: { nilai: ModePeriode; label: string }[] = [
  { nilai: "bulan", label: "Bulan" },
  { nilai: "tahun", label: "Tahun" },
  { nilai: "rentang", label: "Rentang" },
];

function isoHariIni() {
  return new Date().toISOString().slice(0, 10);
}

export function ExportExcel({ items }: { items: Transaksi[] }) {
  const [open, setOpen] = useState(false);
  const [mode, setMode] = useState<ModePeriode>("bulan");
  const [bulan, setBulan] = useState(isoHariIni().slice(0, 7));
  const [tahun, setTahun] = useState(isoHariIni().slice(0, 4));
  const [dari, setDari] = useState(isoHariIni().slice(0, 8) + "01");
  const [sampai, setSampai] = useState(isoHariIni());
  const [loading, setLoading] = useState(false);

  async function jalankan() {
    const opsi: OpsiExport = { mode, bulan, tahun, dari, sampai };
    if (mode === "rentang" && dari > sampai) {
      toast.error("Tanggal awal tidak boleh melebihi tanggal akhir");
      return;
    }
    if (mode === "tahun" && !/^\d{4}$/.test(tahun)) {
      toast.error("Tahun tidak valid");
      return;
    }
    const terpilih = saringPeriode(items, opsi);
    if (terpilih.length === 0) {
      toast.error("Tidak ada transaksi pada periode tersebut");
      return;
    }
    setLoading(true);
    try {
      await exportTransaksiXlsx(terpilih, opsi);
      toast.success(`Berhasil mengekspor ${terpilih.length} transaksi ke Excel`);
      setOpen(false);
    } catch {
      toast.error("Gagal mengekspor file Excel");
    } finally {
      setLoading(false);
    }
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button size="sm" variant="outline" className="gap-1.5">
          <Download className="size-4" /> Export
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Export Excel</DialogTitle>
          <DialogDescription>
            Unduh riwayat transaksi dalam format .xlsx sesuai periode pilihanmu.
          </DialogDescription>
        </DialogHeader>

        <div className="grid grid-cols-3 gap-2 rounded-2xl bg-muted p-1">
          {MODE.map((m) => (
            <button
              key={m.nilai}
              type="button"
              onClick={() => setMode(m.nilai)}
              className={cn(
                "rounded-xl py-2 text-sm font-medium transition-colors",
                mode === m.nilai
                  ? "bg-card text-foreground shadow-sm"
                  : "text-muted-foreground hover:text-foreground",
              )}
            >
              {m.label}
            </button>
          ))}
        </div>

        {mode === "bulan" && (
          <div className="space-y-1.5">
            <Label htmlFor="ex-bulan">Pilih bulan</Label>
            <Input
              id="ex-bulan"
              type="month"
              value={bulan}
              onChange={(e) => setBulan(e.target.value)}
            />
          </div>
        )}

        {mode === "tahun" && (
          <div className="space-y-1.5">
            <Label htmlFor="ex-tahun">Pilih tahun</Label>
            <Input
              id="ex-tahun"
              inputMode="numeric"
              maxLength={4}
              value={tahun}
              onChange={(e) => setTahun(e.target.value.replace(/[^\d]/g, ""))}
            />
          </div>
        )}

        {mode === "rentang" && (
          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1.5">
              <Label htmlFor="ex-dari">Dari</Label>
              <Input
                id="ex-dari"
                type="date"
                value={dari}
                onChange={(e) => setDari(e.target.value)}
              />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="ex-sampai">Sampai</Label>
              <Input
                id="ex-sampai"
                type="date"
                value={sampai}
                onChange={(e) => setSampai(e.target.value)}
              />
            </div>
          </div>
        )}

        <Button onClick={jalankan} disabled={loading} size="lg" className="w-full gap-2">
          {loading ? <Loader2 className="size-4 animate-spin" /> : <Download className="size-4" />}
          Unduh .xlsx
        </Button>
      </DialogContent>
    </Dialog>
  );
}
