import { useState, useMemo } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
  Dialog, DialogContent, DialogHeader, DialogTitle,
} from "@/components/ui/dialog";
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from "@/components/ui/table";
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Trash2, User, Wallet, BarChart3, Pencil, X as XIcon } from "lucide-react";
import { toast } from "sonner";
import { usePermissions } from "@/hooks/use-permissions";
import { useLanguage } from "@/hooks/use-language";

type Staff = {
  id: string;
  name: string;
  salary: number;
  mobile?: string;
  email?: string;
  address?: string;
  role?: string;
  designation?: string;
  nid?: string;
  joining_date?: string | null;
  commission_rate?: number;
  status?: string;
  note?: string;
};

type Payment = {
  id: string;
  staff_id: string;
  pay_month: number;
  pay_year: number;
  basic_salary: number;
  bonus: number;
  deduction: number;
  net_amount: number;
  payment_method: string;
  paid_date: string | null;
  status: string;
  note: string;
  created_at: string;
};

export function StaffSalaryDialog({
  staff, open, onOpenChange,
}: {
  staff: Staff | null;
  open: boolean;
  onOpenChange: (o: boolean) => void;
}) {
  const qc = useQueryClient();
  const { isAdmin } = usePermissions();
  const { tr } = useLanguage();

  const MONTHS = [
    tr("monthJan"), tr("monthFeb"), tr("monthMar"), tr("monthApr"),
    tr("monthMay"), tr("monthJun"), tr("monthJul"), tr("monthAug"),
    tr("monthSep"), tr("monthOct"), tr("monthNov"), tr("monthDec"),
  ];

  const now = new Date();
  const [month, setMonth] = useState<number>(now.getMonth() + 1);
  const [year, setYear] = useState<number>(now.getFullYear());
  const [basic, setBasic] = useState<string>("0");
  const [bonus, setBonus] = useState<string>("0");
  const [deduction, setDeduction] = useState<string>("0");
  const [paymentMethod, setPaymentMethod] = useState<string>("cash");
  const [paidDate, setPaidDate] = useState<string>(now.toISOString().slice(0, 10));
  const [note, setNote] = useState<string>("");

  const [editMode, setEditMode] = useState(false);
  const [editForm, setEditForm] = useState({
    mobile: "", email: "", address: "", nid: "", joining_date: "",
  });

  const { data: payments = [] } = useQuery({
    queryKey: ["staff-salary", staff?.id],
    enabled: !!staff?.id && open,
    queryFn: async () => {
      const { data, error } = await supabase
        .from("staff_salary_payments")
        .select("*")
        .eq("staff_id", staff!.id)
        .order("pay_year", { ascending: false })
        .order("pay_month", { ascending: false });
      if (error) throw error;
      return data as Payment[];
    },
  });

  useMemo(() => {
    if (open && staff) {
      setBasic(String(staff.salary || 0));
      setBonus("0");
      setDeduction("0");
      setNote("");
      setMonth(now.getMonth() + 1);
      setYear(now.getFullYear());
      setPaidDate(now.toISOString().slice(0, 10));
      setEditMode(false);
      setEditForm({
        mobile: staff.mobile || "",
        email: staff.email || "",
        address: staff.address || "",
        nid: staff.nid || "",
        joining_date: staff.joining_date || "",
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, staff?.id]);

  const net = (Number(basic) || 0) + (Number(bonus) || 0) - (Number(deduction) || 0);

  const totals = useMemo(() => {
    const paid = payments.reduce((s, p) => s + Number(p.net_amount), 0);
    return { paid, count: payments.length };
  }, [payments]);

  const saveMutation = useMutation({
    mutationFn: async () => {
      if (!staff) return;
      const payload = {
        staff_id: staff.id,
        pay_month: month,
        pay_year: year,
        basic_salary: Number(basic) || 0,
        bonus: Number(bonus) || 0,
        deduction: Number(deduction) || 0,
        net_amount: net,
        payment_method: paymentMethod,
        paid_date: paidDate || null,
        status: "paid",
        note: note.trim(),
      };
      const { error } = await supabase.from("staff_salary_payments").insert(payload);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success(tr("salaryPaymentSaved"));
      qc.invalidateQueries({ queryKey: ["staff-salary", staff?.id] });
      setBonus("0"); setDeduction("0"); setNote("");
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      const { error } = await supabase.from("staff_salary_payments").delete().eq("id", id);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success(tr("deletedMsg"));
      qc.invalidateQueries({ queryKey: ["staff-salary", staff?.id] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const updateInfoMutation = useMutation({
    mutationFn: async () => {
      if (!staff) return;
      const { error } = await supabase
        .from("staff")
        .update({
          mobile: editForm.mobile.trim(),
          email: editForm.email.trim(),
          address: editForm.address.trim(),
          nid: editForm.nid.trim(),
          joining_date: editForm.joining_date || null,
        })
        .eq("id", staff.id);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success(tr("staffUpdated"));
      qc.invalidateQueries({ queryKey: ["staff"] });
      setEditMode(false);
    },
    onError: (e: Error) => toast.error(e.message),
  });

  if (!staff) return null;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{tr("salaryMgmt")} — {staff.name}</DialogTitle>
        </DialogHeader>

        <Tabs defaultValue="basic" className="w-full">
          <TabsList className="grid w-full grid-cols-3">
            <TabsTrigger value="basic"><User className="h-4 w-4 mr-1" />{tr("basicInfo")}</TabsTrigger>
            <TabsTrigger value="salary"><Wallet className="h-4 w-4 mr-1" />{tr("salaryMgmt")}</TabsTrigger>
            <TabsTrigger value="summary"><BarChart3 className="h-4 w-4 mr-1" />{tr("accountSummary")}</TabsTrigger>
          </TabsList>

          <TabsContent value="basic" className="mt-4">
            <Card className="p-4">
              <div className="flex justify-end mb-3 gap-2">
                {editMode ? (
                  <>
                    <Button size="sm" variant="outline" onClick={() => setEditMode(false)}>
                      <XIcon className="h-4 w-4 mr-1" />{tr("staffCancel")}
                    </Button>
                    <Button size="sm" onClick={() => updateInfoMutation.mutate()} disabled={updateInfoMutation.isPending}>
                      {updateInfoMutation.isPending ? tr("staffSaving") : tr("saveBtn")}
                    </Button>
                  </>
                ) : (
                  isAdmin && (
                    <Button size="sm" variant="outline" onClick={() => setEditMode(true)}>
                      <Pencil className="h-4 w-4 mr-1" />{tr("editStaff")}
                    </Button>
                  )
                )}
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
                <div><div className="text-xs text-muted-foreground">{tr("userName")}</div><div className="font-medium">{staff.name}</div></div>
                <div>
                  <div className="text-xs text-muted-foreground">{tr("mobileLabel")}</div>
                  {editMode
                    ? <Input value={editForm.mobile} onChange={(e) => setEditForm({ ...editForm, mobile: e.target.value })} />
                    : <div className="font-medium">{staff.mobile || "-"}</div>}
                </div>
                <div>
                  <div className="text-xs text-muted-foreground">{tr("emailLabel")}</div>
                  {editMode
                    ? <Input type="email" value={editForm.email} onChange={(e) => setEditForm({ ...editForm, email: e.target.value })} />
                    : <div className="font-medium">{staff.email || "-"}</div>}
                </div>
                <div>
                  <div className="text-xs text-muted-foreground">NID</div>
                  {editMode
                    ? <Input value={editForm.nid} onChange={(e) => setEditForm({ ...editForm, nid: e.target.value })} />
                    : <div className="font-medium">{staff.nid || "-"}</div>}
                </div>
                <div><div className="text-xs text-muted-foreground">{tr("roleLabel")}</div><div className="font-medium capitalize">{staff.role || "-"}</div></div>
                <div><div className="text-xs text-muted-foreground">{tr("designation")}</div><div className="font-medium">{staff.designation || "-"}</div></div>
                <div>
                  <div className="text-xs text-muted-foreground">{tr("joiningDate")}</div>
                  {editMode
                    ? <Input type="date" value={editForm.joining_date} onChange={(e) => setEditForm({ ...editForm, joining_date: e.target.value })} />
                    : <div className="font-medium">{staff.joining_date || "-"}</div>}
                </div>
                <div><div className="text-xs text-muted-foreground">{tr("staffStatusLabel")}</div><div><Badge variant={staff.status === "active" ? "default" : "outline"}>{staff.status || "-"}</Badge></div></div>
                <div><div className="text-xs text-muted-foreground">{tr("monthlySalary")}</div><div className="font-medium">৳{Number(staff.salary || 0).toLocaleString()}</div></div>
                <div><div className="text-xs text-muted-foreground">{tr("commissionRate")}</div><div className="font-medium">{Number(staff.commission_rate || 0)}%</div></div>
                <div className="md:col-span-2">
                  <div className="text-xs text-muted-foreground">{tr("addressLabel")}</div>
                  {editMode
                    ? <Textarea rows={2} value={editForm.address} onChange={(e) => setEditForm({ ...editForm, address: e.target.value })} />
                    : <div className="font-medium">{staff.address || "-"}</div>}
                </div>
                {!editMode && staff.note && <div className="md:col-span-2"><div className="text-xs text-muted-foreground">{tr("noteLabel")}</div><div className="font-medium">{staff.note}</div></div>}
              </div>
            </Card>
          </TabsContent>

          <TabsContent value="salary" className="mt-4">
            <div className="grid grid-cols-2 md:grid-cols-3 gap-3 mb-4">
              <Card className="p-3">
                <div className="text-xs text-muted-foreground">{tr("basicSalary")}</div>
                <div className="text-lg font-semibold">৳{Number(staff.salary).toLocaleString()}</div>
              </Card>
              <Card className="p-3">
                <div className="text-xs text-muted-foreground">{tr("totalPayments")}</div>
                <div className="text-lg font-semibold">{totals.count}</div>
              </Card>
              <Card className="p-3">
                <div className="text-xs text-muted-foreground">{tr("staffTotalPaid")}</div>
                <div className="text-lg font-semibold text-green-600">৳{totals.paid.toLocaleString()}</div>
              </Card>
            </div>

            {isAdmin && (
              <Card className="p-4 mb-4 bg-muted/30">
                <div className="font-medium mb-3">{tr("newSalaryPayment")}</div>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                  <div>
                    <Label>{tr("monthLabel")}</Label>
                    <Select value={String(month)} onValueChange={(v) => setMonth(Number(v))}>
                      <SelectTrigger><SelectValue /></SelectTrigger>
                      <SelectContent>
                        {MONTHS.map((m, i) => <SelectItem key={i} value={String(i + 1)}>{m}</SelectItem>)}
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label>{tr("yearLabel")}</Label>
                    <Input type="number" value={year} onChange={(e) => setYear(Number(e.target.value))} />
                  </div>
                  <div>
                    <Label>{tr("staffPaymentMethod")}</Label>
                    <Select value={paymentMethod} onValueChange={setPaymentMethod}>
                      <SelectTrigger><SelectValue /></SelectTrigger>
                      <SelectContent>
                        <SelectItem value="cash">{tr("salaryPayMethodCash")}</SelectItem>
                        <SelectItem value="bank">{tr("salaryPayMethodBank")}</SelectItem>
                        <SelectItem value="bkash">{tr("salaryPayMethodBkash")}</SelectItem>
                        <SelectItem value="nagad">{tr("salaryPayMethodNagad")}</SelectItem>
                        <SelectItem value="other">{tr("salaryPayMethodOther")}</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label>{tr("paymentDate")}</Label>
                    <Input type="date" value={paidDate} onChange={(e) => setPaidDate(e.target.value)} />
                  </div>
                  <div>
                    <Label>{tr("basicSalaryInput")}</Label>
                    <Input type="number" min="0" value={basic} onChange={(e) => setBasic(e.target.value)} />
                  </div>
                  <div>
                    <Label>{tr("bonusPlus")}</Label>
                    <Input type="number" min="0" value={bonus} onChange={(e) => setBonus(e.target.value)} />
                  </div>
                  <div>
                    <Label>{tr("deductionMinus")}</Label>
                    <Input type="number" min="0" value={deduction} onChange={(e) => setDeduction(e.target.value)} />
                  </div>
                  <div>
                    <Label>{tr("netSalary")}</Label>
                    <div className="h-10 px-3 flex items-center rounded-md border bg-background font-semibold text-primary">
                      ৳{net.toLocaleString()}
                    </div>
                  </div>
                  <div className="md:col-span-4">
                    <Label>{tr("noteLabel")}</Label>
                    <Textarea rows={2} value={note} onChange={(e) => setNote(e.target.value)} />
                  </div>
                </div>
                <div className="flex justify-end mt-3">
                  <Button onClick={() => saveMutation.mutate()} disabled={saveMutation.isPending}>
                    {saveMutation.isPending ? tr("staffSaving") : tr("savePayment")}
                  </Button>
                </div>
              </Card>
            )}

            <div className="font-medium mb-2">{tr("staffPaymentHistory")}</div>
            <div className="border rounded-lg overflow-hidden">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>{tr("monthLabel")}</TableHead>
                    <TableHead className="text-right">{tr("basicCol")}</TableHead>
                    <TableHead className="text-right">{tr("bonusCol")}</TableHead>
                    <TableHead className="text-right">{tr("deductionCol")}</TableHead>
                    <TableHead className="text-right">{tr("netCol")}</TableHead>
                    <TableHead>{tr("methodCol")}</TableHead>
                    <TableHead>{tr("dateCol")}</TableHead>
                    <TableHead>{tr("staffStatusLabel")}</TableHead>
                    {isAdmin && <TableHead></TableHead>}
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {payments.length === 0 ? (
                    <TableRow><TableCell colSpan={isAdmin ? 9 : 8} className="text-center py-6 text-muted-foreground">{tr("noPayments")}</TableCell></TableRow>
                  ) : payments.map((p) => (
                    <TableRow key={p.id}>
                      <TableCell>{MONTHS[p.pay_month - 1]} {p.pay_year}</TableCell>
                      <TableCell className="text-right">৳{Number(p.basic_salary).toLocaleString()}</TableCell>
                      <TableCell className="text-right text-green-600">+৳{Number(p.bonus).toLocaleString()}</TableCell>
                      <TableCell className="text-right text-destructive">−৳{Number(p.deduction).toLocaleString()}</TableCell>
                      <TableCell className="text-right font-semibold">৳{Number(p.net_amount).toLocaleString()}</TableCell>
                      <TableCell className="capitalize">{p.payment_method}</TableCell>
                      <TableCell>{p.paid_date || "-"}</TableCell>
                      <TableCell><Badge variant="default">{p.status}</Badge></TableCell>
                      {isAdmin && (
                        <TableCell>
                          <Button size="icon" variant="ghost" onClick={() => deleteMutation.mutate(p.id)}>
                            <Trash2 className="h-4 w-4 text-destructive" />
                          </Button>
                        </TableCell>
                      )}
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </TabsContent>

          <TabsContent value="summary" className="mt-4">
            {(() => {
              const totalBasic = payments.reduce((s, p) => s + Number(p.basic_salary), 0);
              const totalBonus = payments.reduce((s, p) => s + Number(p.bonus), 0);
              const totalDed = payments.reduce((s, p) => s + Number(p.deduction), 0);
              const last = payments[0];
              const yearMap: Record<number, number> = {};
              payments.forEach((p) => { yearMap[p.pay_year] = (yearMap[p.pay_year] || 0) + Number(p.net_amount); });
              return (
                <div className="space-y-4">
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                    <Card className="p-3"><div className="text-xs text-muted-foreground">{tr("totalPayments")}</div><div className="text-lg font-semibold">{totals.count}</div></Card>
                    <Card className="p-3"><div className="text-xs text-muted-foreground">{tr("staffTotalPaid")}</div><div className="text-lg font-semibold text-green-600">৳{totals.paid.toLocaleString()}</div></Card>
                    <Card className="p-3"><div className="text-xs text-muted-foreground">{tr("bonusCol")}</div><div className="text-lg font-semibold text-green-600">+৳{totalBonus.toLocaleString()}</div></Card>
                    <Card className="p-3"><div className="text-xs text-muted-foreground">{tr("deductionCol")}</div><div className="text-lg font-semibold text-destructive">−৳{totalDed.toLocaleString()}</div></Card>
                  </div>
                  <Card className="p-4">
                    <div className="font-medium mb-2">{tr("basicSalary")} ({tr("totalPayments")})</div>
                    <div className="text-2xl font-bold">৳{totalBasic.toLocaleString()}</div>
                    {last && (
                      <div className="text-xs text-muted-foreground mt-2">
                        {tr("paymentDate")}: {MONTHS[last.pay_month - 1]} {last.pay_year} — ৳{Number(last.net_amount).toLocaleString()}
                      </div>
                    )}
                  </Card>
                  {Object.keys(yearMap).length > 0 && (
                    <Card className="p-4">
                      <div className="font-medium mb-2">{tr("yearLabel")}</div>
                      <div className="space-y-1 text-sm">
                        {Object.entries(yearMap).sort((a, b) => Number(b[0]) - Number(a[0])).map(([y, amt]) => (
                          <div key={y} className="flex justify-between border-b last:border-0 py-1">
                            <span>{y}</span>
                            <span className="font-semibold">৳{amt.toLocaleString()}</span>
                          </div>
                        ))}
                      </div>
                    </Card>
                  )}
                </div>
              );
            })()}
          </TabsContent>
        </Tabs>
      </DialogContent>
    </Dialog>
  );
}
