"use client";

import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { apiGet, apiPatch, apiPost } from "@/lib/api/client";
import { useAuthStore } from "@/lib/stores/auth.store";
import { formatCurrency, formatNumber } from "@/lib/format";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { LabeledField } from "@/components/ui/labeled-field";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";

interface Employee {
  id: string;
  name: string;
  phone: string;
  role: string;
  baseSalary: number;
}

interface Attendance {
  id: string;
  employeeId: string;
  employeeName: string;
  date: string;
  clockIn?: string;
  clockOut?: string;
}

interface LeaveRequest {
  id: string;
  employeeName: string;
  startDate: string;
  endDate: string;
  reason?: string;
  status: string;
}

interface Salary {
  id: string;
  employeeName: string;
  monthYear: string;
  netSalary: number;
  isPaid: boolean;
}

type Tab = "attendance" | "leave" | "payroll";

export function HrScreen() {
  const t = useTranslations("hr");
  const cafeId = useAuthStore((s) => s.user?.cafeId);
  const userId = useAuthStore((s) => s.user?.userId);
  const queryClient = useQueryClient();
  const [tab, setTab] = useState<Tab>("attendance");
  const [monthYear, setMonthYear] = useState(
    new Date().toISOString().slice(0, 7)
  );

  const { data: employees = [] } = useQuery({
    queryKey: ["employees", cafeId],
    queryFn: () => apiGet<Employee[]>(`/api/cafes/${cafeId}/employees`),
    enabled: !!cafeId,
  });

  const { data: attendance = [] } = useQuery({
    queryKey: ["attendance", cafeId],
    queryFn: () => apiGet<Attendance[]>(`/api/cafes/${cafeId}/attendance`),
    enabled: !!cafeId && tab === "attendance",
  });

  const { data: leaves = [] } = useQuery({
    queryKey: ["leave-requests", cafeId],
    queryFn: () =>
      apiGet<LeaveRequest[]>(`/api/cafes/${cafeId}/leave-requests?status=Pending`),
    enabled: !!cafeId && tab === "leave",
  });

  const { data: salaries = [] } = useQuery({
    queryKey: ["salaries", cafeId, monthYear],
    queryFn: () =>
      apiGet<Salary[]>(`/api/cafes/${cafeId}/salaries?monthYear=${monthYear}`),
    enabled: !!cafeId && tab === "payroll",
  });

  const clockIn = useMutation({
    mutationFn: () =>
      apiPost<Attendance>(`/api/cafes/${cafeId}/employees/${userId}/attendance/clock-in`),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ["attendance", cafeId] }),
  });

  const clockOut = useMutation({
    mutationFn: () =>
      apiPost<Attendance>(`/api/cafes/${cafeId}/employees/${userId}/attendance/clock-out`),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ["attendance", cafeId] }),
  });

  const approveLeave = useMutation({
    mutationFn: (leaveId: string) =>
      apiPatch(`/api/cafes/${cafeId}/leave-requests/${leaveId}/status`, {
        status: "Approved",
      }),
    onSuccess: () =>
      queryClient.invalidateQueries({ queryKey: ["leave-requests", cafeId] }),
  });

  const markPaid = useMutation({
    mutationFn: (salaryId: string) =>
      apiPatch(`/api/cafes/${cafeId}/salaries/${salaryId}/paid`),
    onSuccess: () =>
      queryClient.invalidateQueries({ queryKey: ["salaries", cafeId, monthYear] }),
  });

  if (!cafeId || !userId) return null;

  return (
    <div className="space-y-4">
      <h2 className="text-xl font-bold">{t("title")}</h2>

      <div className="flex flex-wrap gap-2">
        {(["attendance", "leave", "payroll"] as Tab[]).map((key) => (
          <Button
            key={key}
            size="sm"
            variant={tab === key ? "default" : "outline"}
            onClick={() => setTab(key)}
          >
            {t(`tabs.${key}`)}
          </Button>
        ))}
      </div>

      {tab === "attendance" && (
        <div className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">{t("myAttendance")}</CardTitle>
            </CardHeader>
            <CardContent className="flex flex-wrap gap-2">
              <Button onClick={() => clockIn.mutate()} disabled={clockIn.isPending}>
                {t("clockIn")}
              </Button>
              <Button variant="outline" onClick={() => clockOut.mutate()} disabled={clockOut.isPending}>
                {t("clockOut")}
              </Button>
            </CardContent>
          </Card>

          <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
            {attendance.map((a) => (
              <Card key={a.id}>
                <CardContent className="space-y-1 pt-4 text-sm">
                  <p className="font-medium">{a.employeeName}</p>
                  <p className="text-muted-foreground">{a.date}</p>
                  <p dir="ltr" className="text-end font-mono text-xs">
                    {a.clockIn ? new Date(a.clockIn).toLocaleTimeString("fa-IR") : "—"}
                    {" → "}
                    {a.clockOut ? new Date(a.clockOut).toLocaleTimeString("fa-IR") : "—"}
                  </p>
                </CardContent>
              </Card>
            ))}
          </div>
        </div>
      )}

      {tab === "leave" && (
        <div className="space-y-3">
          {leaves.length === 0 ? (
            <p className="text-muted-foreground">{t("noLeave")}</p>
          ) : (
            leaves.map((l) => (
              <Card key={l.id}>
                <CardContent className="flex flex-wrap items-center justify-between gap-3 pt-4">
                  <div>
                    <p className="font-medium">{l.employeeName}</p>
                    <p className="text-sm text-muted-foreground">
                      {l.startDate} — {l.endDate}
                    </p>
                    {l.reason && <p className="text-sm">{l.reason}</p>}
                  </div>
                  <Button size="sm" onClick={() => approveLeave.mutate(l.id)}>
                    {t("approve")}
                  </Button>
                </CardContent>
              </Card>
            ))
          )}
        </div>
      )}

      {tab === "payroll" && (
        <div className="space-y-4">
          <LabeledField label={t("monthYear")} htmlFor="hr-month" hint="YYYY-MM" className="max-w-xs">
            <Input
              id="hr-month"
              value={monthYear}
              onChange={(e) => setMonthYear(e.target.value)}
              dir="ltr"
              className="text-end"
            />
          </LabeledField>
          <p className="text-sm text-muted-foreground">
            {t("employeeCount")}: {formatNumber(employees.length)}
          </p>
          {salaries.map((s) => (
            <Card key={s.id}>
              <CardContent className="flex items-center justify-between pt-4">
                <div>
                  <p className="font-medium">{s.employeeName}</p>
                  <p>{formatCurrency(s.netSalary)}</p>
                </div>
                {s.isPaid ? (
                  <Badge>{t("paid")}</Badge>
                ) : (
                  <Button size="sm" onClick={() => markPaid.mutate(s.id)}>
                    {t("markPaid")}
                  </Button>
                )}
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}
