"use client";

import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import MainTitle from "@/components/layout/dashboard/main-title";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { PhoneInput } from "@/components/ui/phone-input";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import DataService from "@/config/axios";
import { useRequireSuperAdmin } from "@/hooks/use-require-super-admin";
import { getApiErrorMessage } from "@/lib/api-error";
import { toast } from "sonner";

type Supplier = {
  _id: string;
  name: string;
  email?: string;
  phone?: string;
  address?: string;
  notes?: string;
  active?: boolean;
};

export default function SuppliersAdmin() {
  const ready = useRequireSuperAdmin();
  const params = useParams();
  const app = params.app as string;
  const [loading, setLoading] = useState(true);
  const [rows, setRows] = useState<Supplier[]>([]);
  const [busy, setBusy] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [form, setForm] = useState({
    name: "",
    email: "",
    phone: "",
    address: "",
    notes: "",
  });

  const load = useCallback(async () => {
    try {
      const res = await DataService.get("/admin/suppliers");
      setRows(res.data?.data || []);
    } catch (e: unknown) {
      toast.error(getApiErrorMessage(e, "Failed to load suppliers"));
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (ready) load();
  }, [ready, load]);

  const resetForm = () => {
    setEditingId(null);
    setForm({ name: "", email: "", phone: "", address: "", notes: "" });
  };

  const save = async (e: React.FormEvent) => {
    e.preventDefault();
    setBusy(true);
    try {
      const payload = {
        name: form.name.trim(),
        email: form.email.trim(),
        phone: form.phone.trim(),
        address: form.address.trim(),
        notes: form.notes.trim(),
        active: true,
      };
      if (editingId) {
        await DataService.patch(`/admin/suppliers/${editingId}`, payload);
        toast.success("Supplier updated");
      } else {
        await DataService.post("/admin/suppliers", payload);
        toast.success("Supplier created");
      }
      resetForm();
      load();
    } catch (err: unknown) {
      toast.error(getApiErrorMessage(err, "Could not save supplier"));
    } finally {
      setBusy(false);
    }
  };

  const startEdit = (row: Supplier) => {
    setEditingId(row._id);
    setForm({
      name: row.name || "",
      email: row.email || "",
      phone: row.phone || "",
      address: row.address || "",
      notes: row.notes || "",
    });
  };

  const toggleActive = async (row: Supplier) => {
    try {
      await DataService.patch(`/admin/suppliers/${row._id}`, { active: !row.active });
      load();
    } catch (e: unknown) {
      toast.error(getApiErrorMessage(e, "Could not update"));
    }
  };

  const remove = async (id: string) => {
    if (!confirm("Delete this supplier?")) return;
    try {
      await DataService.delete(`/admin/suppliers/${id}`);
      toast.success("Deleted");
      load();
    } catch (e: unknown) {
      toast.error(getApiErrorMessage(e, "Could not delete"));
    }
  };

  if (!ready || loading) {
    return <div className="rounded-md border bg-white p-8 text-center text-gray-500">Loading…</div>;
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div>
          <MainTitle title="Suppliers & bills" />
          <p className="text-sm text-gray-500">Manage vendors and their purchase bills.</p>
        </div>
        <Button type="button" variant="outline" asChild>
          <Link href={`/${app}/admin/suppliers/bills`}>View all bills</Link>
        </Button>
      </div>

      <form onSubmit={save} className="grid gap-3 rounded-md border bg-white p-4 md:grid-cols-2">
        <div className="grid gap-2">
          <Label>Name</Label>
          <Input
            value={form.name}
            onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
            required
          />
        </div>
        <div className="grid gap-2">
          <Label>Email</Label>
          <Input
            type="email"
            value={form.email}
            onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))}
          />
        </div>
        <div className="grid gap-2">
          <Label>Phone</Label>
          <PhoneInput
            value={form.phone}
            onChange={(phone) => setForm((f) => ({ ...f, phone }))}
          />
        </div>
        <div className="grid gap-2">
          <Label>Address</Label>
          <Input
            value={form.address}
            onChange={(e) => setForm((f) => ({ ...f, address: e.target.value }))}
          />
        </div>
        <div className="grid gap-2 md:col-span-2">
          <Label>Notes</Label>
          <Input
            value={form.notes}
            onChange={(e) => setForm((f) => ({ ...f, notes: e.target.value }))}
          />
        </div>
        <div className="flex gap-2 md:col-span-2">
          <Button type="submit" disabled={busy}>
            {busy ? "Saving…" : editingId ? "Update supplier" : "Add supplier"}
          </Button>
          {editingId ? (
            <Button type="button" variant="outline" onClick={resetForm}>
              Cancel edit
            </Button>
          ) : null}
        </div>
      </form>

      <div className="rounded-md border bg-white">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Name</TableHead>
              <TableHead>Contact</TableHead>
              <TableHead>Active</TableHead>
              <TableHead />
            </TableRow>
          </TableHeader>
          <TableBody>
            {rows.length === 0 ? (
              <TableRow>
                <TableCell colSpan={4} className="text-center text-gray-400">
                  No suppliers yet.
                </TableCell>
              </TableRow>
            ) : (
              rows.map((r) => (
                <TableRow key={r._id}>
                  <TableCell className="font-medium">{r.name}</TableCell>
                  <TableCell className="text-sm text-gray-600">
                    {[r.email, r.phone].filter(Boolean).join(" · ") || "—"}
                  </TableCell>
                  <TableCell>{r.active === false ? "No" : "Yes"}</TableCell>
                  <TableCell className="space-x-2 text-right">
                    <Button type="button" size="sm" variant="outline" asChild>
                      <Link href={`/${app}/admin/suppliers/bills/new?supplier=${r._id}`}>
                        New bill
                      </Link>
                    </Button>
                    <Button type="button" size="sm" variant="outline" onClick={() => startEdit(r)}>
                      Edit
                    </Button>
                    <Button type="button" size="sm" variant="outline" onClick={() => toggleActive(r)}>
                      {r.active === false ? "Enable" : "Disable"}
                    </Button>
                    <Button type="button" size="sm" variant="outline" onClick={() => remove(r._id)}>
                      Delete
                    </Button>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}
