import { createFileRoute } from "@tanstack/react-router";
import { useServerFn } from "@tanstack/react-start";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import {
  adminListPortalCustomers,
  adminSetPortalPassword,
  adminCreatePortalCustomer,
  adminUpdatePortalCustomer,
  adminDeletePortalCustomer,
} from "@/lib/customer-portal.functions";
import { PageLayout } from "@/components/PageLayout";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import {
  AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
  AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { toast } from "sonner";
import { KeyRound, Search, ShieldAlert, Plus, Pencil, Trash2, LogIn, ExternalLink } from "lucide-react";
import { useAuth } from "@/hooks/use-auth";
import { supabase } from "@/integrations/supabase/client";

export const Route = createFileRoute("/_authenticated/portal-access")({
  head: () => ({ meta: [{ title: "Customer Portal Access — Niyamah ERP" }] }),
  component: PortalAccessPage,
});

type Row = {
  id: string; name: string; name_bn: string; mobile: string;
  email: string; address: string;
  status: string; portal_last_login_at: string | null;
  portal_enabled: boolean; has_password: boolean;
};

type FormState = { name: string; name_bn: string; mobile: string; email: string; address: string; password: string; portal_enabled: boolean; status: "active" | "inactive" };
const emptyForm: FormState = { name: "", name_bn: "", mobile: "", email: "", address: "", password: "", portal_enabled: true, status: "active" };

function formatLastLogin(iso: string | null): string {
  if (!iso) return "—";
  try {
    const d = new Date(iso);
    return d.toLocaleString("en-GB", { day: "2-digit", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" });
  } catch { return "—"; }
}

function PortalAccessPage() {
  const { user } = useAuth();
  const qc = useQueryClient();
  const [search, setSearch] = useState("");
  const [pwTarget, setPwTarget] = useState<{ id: string; name: string } | null>(null);
  const [pw, setPw] = useState("");
  const [editTarget, setEditTarget] = useState<Row | null>(null);
  const [createOpen, setCreateOpen] = useState(false);
  const [form, setForm] = useState<FormState>(emptyForm);
  const [deleteTarget, setDeleteTarget] = useState<Row | null>(null);

  const { data: isAdmin = false } = useQuery({
    queryKey: ["is-admin", user?.id],
    enabled: !!user?.id,
    queryFn: async () => {
      const { data } = await supabase.from("user_roles").select("role").eq("user_id", user!.id).eq("role", "admin").maybeSingle();
      return !!data;
    },
  });

  const list = useServerFn(adminListPortalCustomers);
  const setPwd = useServerFn(adminSetPortalPassword);
  const createFn = useServerFn(adminCreatePortalCustomer);
  const updateFn = useServerFn(adminUpdatePortalCustomer);
  const deleteFn = useServerFn(adminDeletePortalCustomer);

  const { data: rows = [] } = useQuery<Row[]>({
    queryKey: ["portal-customers", search],
    enabled: isAdmin,
    queryFn: async () => {
      const res: any = await list({ data: { search } });
      return Array.isArray(res) ? res : Array.isArray(res?.result) ? res.result : [];
    },
  });

  const invalidate = () => qc.invalidateQueries({ queryKey: ["portal-customers"] });

  const toggleMut = useMutation({
    mutationFn: async ({ id, enabled }: { id: string; enabled: boolean }) =>
      setPwd({ data: { customer_id: id, enabled } }),
    onSuccess: () => { invalidate(); toast.success("আপডেট হয়েছে"); },
    onError: (e: any) => toast.error(e.message),
  });

  const setPwMut = useMutation({
    mutationFn: async () => {
      if (!pwTarget) return;
      if (pw.length < 4) throw new Error("কমপক্ষে ৪ অক্ষর");
      await setPwd({ data: { customer_id: pwTarget.id, password: pw, enabled: true } });
    },
    onSuccess: () => { invalidate(); toast.success("পাসওয়ার্ড সেট হয়েছে"); setPwTarget(null); setPw(""); },
    onError: (e: any) => toast.error(e.message),
  });

  const createMut = useMutation({
    mutationFn: async () => {
      if (!form.name.trim()) throw new Error("নাম দিন");
      if (!form.mobile.trim()) throw new Error("মোবাইল দিন");
      await createFn({ data: {
        name: form.name, name_bn: form.name_bn, mobile: form.mobile,
        email: form.email || undefined, address: form.address,
        password: form.password || undefined, portal_enabled: form.portal_enabled,
      } });
    },
    onSuccess: () => { invalidate(); toast.success("কাস্টমার তৈরি হয়েছে"); setCreateOpen(false); setForm(emptyForm); },
    onError: (e: any) => toast.error(e.message),
  });

  const updateMut = useMutation({
    mutationFn: async () => {
      if (!editTarget) return;
      await updateFn({ data: {
        customer_id: editTarget.id,
        name: form.name, name_bn: form.name_bn, mobile: form.mobile,
        email: form.email, address: form.address, status: form.status,
      } });
    },
    onSuccess: () => { invalidate(); toast.success("আপডেট হয়েছে"); setEditTarget(null); setForm(emptyForm); },
    onError: (e: any) => toast.error(e.message),
  });

  const deleteMut = useMutation({
    mutationFn: async () => {
      if (!deleteTarget) return;
      await deleteFn({ data: { customer_id: deleteTarget.id } });
    },
    onSuccess: () => { invalidate(); toast.success("ডিলিট হয়েছে"); setDeleteTarget(null); },
    onError: (e: any) => toast.error(e.message),
  });

  const openCreate = () => { setForm(emptyForm); setCreateOpen(true); };
  const openEdit = (r: Row) => {
    setEditTarget(r);
    setForm({ name: r.name, name_bn: r.name_bn || "", mobile: r.mobile, email: r.email || "", address: r.address || "", password: "", portal_enabled: r.portal_enabled, status: (r.status === "inactive" ? "inactive" : "active") });
  };

  if (!isAdmin) {
    return (
      <PageLayout>
        <div className="rounded-2xl border border-destructive/30 bg-destructive/5 p-8 text-center">
          <ShieldAlert className="h-10 w-10 mx-auto text-destructive mb-2" />
          <h1 className="text-xl font-bold">অনুমতি নেই</h1>
        </div>
      </PageLayout>
    );
  }

  return (
    <PageLayout title="কাস্টমার পোর্টাল অ্যাকসেস" subtitle="কাস্টমার যোগ/এডিট/ডিলিট ও পোর্টাল লগইন ম্যানেজ করুন">
      <div className="mb-4 flex items-center gap-2">
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input className="pl-9" value={search} onChange={(e) => setSearch(e.target.value)} placeholder="নাম বা মোবাইল" />
        </div>
        <Button variant="outline" asChild>
          <a href="/portal/login" target="_blank" rel="noreferrer"><ExternalLink className="h-4 w-4 mr-1" />পোর্টাল লগইন পেজ</a>
        </Button>
        <Button onClick={openCreate}><Plus className="h-4 w-4 mr-1" />নতুন কাস্টমার</Button>
      </div>

      <div className="rounded-lg border bg-card">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>নাম</TableHead>
              <TableHead>মোবাইল</TableHead>
              <TableHead>স্ট্যাটাস</TableHead>
              <TableHead>পোর্টাল চালু</TableHead>
              <TableHead>পাসওয়ার্ড</TableHead>
              <TableHead>সর্বশেষ লগইন</TableHead>
              <TableHead className="text-right">অ্যাকশন</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {rows.length === 0 ? (
              <TableRow><TableCell colSpan={7} className="text-center py-8 text-muted-foreground">কোনো কাস্টমার নেই</TableCell></TableRow>
            ) : rows.map((r) => (
              <TableRow key={r.id}>
                <TableCell>{r.name_bn || r.name}</TableCell>
                <TableCell className="font-mono text-sm">{r.mobile}</TableCell>
                <TableCell>
                  {r.status === "inactive"
                    ? <Badge variant="secondary">নিষ্ক্রিয়</Badge>
                    : <Badge className="bg-emerald-500/15 text-emerald-700 hover:bg-emerald-500/15 dark:text-emerald-400">সক্রিয়</Badge>}
                </TableCell>
                <TableCell>
                  <Switch checked={r.portal_enabled} onCheckedChange={(v) => toggleMut.mutate({ id: r.id, enabled: v })} />
                </TableCell>
                <TableCell>
                  {r.has_password ? <Badge>সেট আছে</Badge> : <Badge variant="secondary">সেট নেই</Badge>}
                </TableCell>
                <TableCell className="text-xs text-muted-foreground whitespace-nowrap">{formatLastLogin(r.portal_last_login_at)}</TableCell>
                <TableCell className="text-right">
                  <div className="flex justify-end gap-1">
                    <Button size="sm" variant="outline" asChild disabled={!r.portal_enabled || !r.has_password}>
                      <a
                        href={`/portal/login?mobile=${encodeURIComponent(r.mobile)}`}
                        target="_blank"
                        rel="noreferrer"
                        title={!r.has_password ? "পাসওয়ার্ড সেট নেই" : !r.portal_enabled ? "পোর্টাল বন্ধ" : "পোর্টাল লগইন পেজ খুলুন"}
                      >
                        <LogIn className="h-3.5 w-3.5 mr-1" />লগইন
                      </a>
                    </Button>
                    <Button size="sm" variant="outline" onClick={() => { setPwTarget({ id: r.id, name: r.name_bn || r.name }); setPw(""); }}>
                      <KeyRound className="h-3.5 w-3.5 mr-1" />পাসওয়ার্ড
                    </Button>
                    <Button size="sm" variant="outline" onClick={() => openEdit(r)}>
                      <Pencil className="h-3.5 w-3.5" />
                    </Button>
                    <Button size="sm" variant="outline" className="text-destructive hover:text-destructive" onClick={() => setDeleteTarget(r)}>
                      <Trash2 className="h-3.5 w-3.5" />
                    </Button>
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>

      {/* Password dialog */}
      <Dialog open={!!pwTarget} onOpenChange={(o) => { if (!o) { setPwTarget(null); setPw(""); } }}>
        <DialogContent>
          <DialogHeader><DialogTitle>পাসওয়ার্ড সেট — {pwTarget?.name}</DialogTitle></DialogHeader>
          <div className="space-y-2">
            <Label>নতুন পাসওয়ার্ড</Label>
            <Input type="text" value={pw} onChange={(e) => setPw(e.target.value)} placeholder="কমপক্ষে ৪ অক্ষর" />
            <p className="text-xs text-muted-foreground">এটি সেট করলে পোর্টাল অ্যাকসেসও স্বয়ংক্রিয়ভাবে চালু হবে।</p>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setPwTarget(null)}>বাতিল</Button>
            <Button onClick={() => setPwMut.mutate()} disabled={setPwMut.isPending}>{setPwMut.isPending ? "..." : "সেট করুন"}</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Create dialog */}
      <Dialog open={createOpen} onOpenChange={(o) => { if (!o) { setCreateOpen(false); setForm(emptyForm); } }}>
        <DialogContent className="max-w-lg">
          <DialogHeader><DialogTitle>নতুন কাস্টমার</DialogTitle></DialogHeader>
          <div className="grid grid-cols-2 gap-3">
            <div className="col-span-1"><Label>নাম *</Label><Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} /></div>
            <div className="col-span-1"><Label>নাম (বাংলা)</Label><Input value={form.name_bn} onChange={(e) => setForm({ ...form, name_bn: e.target.value })} /></div>
            <div className="col-span-1"><Label>মোবাইল *</Label><Input value={form.mobile} onChange={(e) => setForm({ ...form, mobile: e.target.value })} placeholder="01XXXXXXXXX" /></div>
            <div className="col-span-1"><Label>ইমেইল</Label><Input value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} /></div>
            <div className="col-span-2"><Label>ঠিকানা</Label><Input value={form.address} onChange={(e) => setForm({ ...form, address: e.target.value })} /></div>
            <div className="col-span-1"><Label>পোর্টাল পাসওয়ার্ড</Label><Input value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} placeholder="কমপক্ষে ৪ অক্ষর (ঐচ্ছিক)" /></div>
            <div className="col-span-1 flex items-end gap-2"><Switch checked={form.portal_enabled} onCheckedChange={(v) => setForm({ ...form, portal_enabled: v })} /><span className="text-sm">পোর্টাল চালু</span></div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => { setCreateOpen(false); setForm(emptyForm); }}>বাতিল</Button>
            <Button onClick={() => createMut.mutate()} disabled={createMut.isPending}>{createMut.isPending ? "..." : "তৈরি করুন"}</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Edit dialog */}
      <Dialog open={!!editTarget} onOpenChange={(o) => { if (!o) { setEditTarget(null); setForm(emptyForm); } }}>
        <DialogContent className="max-w-lg">
          <DialogHeader><DialogTitle>এডিট — {editTarget?.name_bn || editTarget?.name}</DialogTitle></DialogHeader>
          <div className="grid grid-cols-2 gap-3">
            <div className="col-span-1"><Label>নাম *</Label><Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} /></div>
            <div className="col-span-1"><Label>নাম (বাংলা)</Label><Input value={form.name_bn} onChange={(e) => setForm({ ...form, name_bn: e.target.value })} /></div>
            <div className="col-span-1"><Label>মোবাইল *</Label><Input value={form.mobile} onChange={(e) => setForm({ ...form, mobile: e.target.value })} /></div>
            <div className="col-span-1"><Label>ইমেইল</Label><Input value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} /></div>
            <div className="col-span-2"><Label>ঠিকানা</Label><Input value={form.address} onChange={(e) => setForm({ ...form, address: e.target.value })} /></div>
            <div className="col-span-2 flex items-center justify-between rounded-md border px-3 py-2">
              <div>
                <p className="text-sm font-medium">অ্যাকাউন্ট স্ট্যাটাস</p>
                <p className="text-xs text-muted-foreground">নিষ্ক্রিয় হলে পোর্টালে লগইন করতে পারবে না।</p>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-xs">{form.status === "active" ? "সক্রিয়" : "নিষ্ক্রিয়"}</span>
                <Switch checked={form.status === "active"} onCheckedChange={(v) => setForm({ ...form, status: v ? "active" : "inactive" })} />
              </div>
            </div>
            <div className="col-span-2 text-xs text-muted-foreground">
              সর্বশেষ লগইন: {formatLastLogin(editTarget?.portal_last_login_at ?? null)}
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => { setEditTarget(null); setForm(emptyForm); }}>বাতিল</Button>
            <Button onClick={() => updateMut.mutate()} disabled={updateMut.isPending}>{updateMut.isPending ? "..." : "সেভ করুন"}</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete confirm */}
      <AlertDialog open={!!deleteTarget} onOpenChange={(o) => { if (!o) setDeleteTarget(null); }}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>কাস্টমার ডিলিট?</AlertDialogTitle>
            <AlertDialogDescription>
              "{deleteTarget?.name_bn || deleteTarget?.name}" কে ডিলিট করা হবে। পোর্টাল লগইনও বন্ধ হয়ে যাবে।
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>বাতিল</AlertDialogCancel>
            <AlertDialogAction className="bg-destructive text-destructive-foreground hover:bg-destructive/90" onClick={() => deleteMut.mutate()} disabled={deleteMut.isPending}>
              {deleteMut.isPending ? "..." : "ডিলিট"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </PageLayout>
  );
}
