import DashboardLayout from "@/components/layout/dashboard-layout";
import { verifySession } from "@/lib/auth";
import { getMonthlyBonuses, getMonthlyDeductions, getNetSalary } from "@/lib/data-helpers";
import AttendanceCard from "@/components/employee/attendance-card";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Briefcase, Clock, UserCheck, TrendingDown, TrendingUp, Wallet, DollarSign } from "lucide-react";
import { format } from 'date-fns';
import { Badge } from "@/components/ui/badge";
import { getTranslations, getCurrentLocale } from "@/lib/i18n";
import MonthYearPicker from "@/components/admin/month-year-picker";
import { getCurrencySymbolAsync } from "@/lib/server-currency";
import { formatCurrency as formatCurrencyUtil } from "@/lib/currency-formatter";
import type { Employee } from "@/lib/types";

export default async function EmployeeDashboardPage({
  searchParams,
}: {
    searchParams?: Promise<{ month?: string; year?: string }>;
}) {
  const { user } = await verifySession();
  if(!user) return null;

  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const tGlobal = t.Global;
  const tEmployeeDashboard = t.EmployeeDashboard;
  const tAttendanceCard = t.AttendanceCard;

  const employee = (((await (await import('@/lib/postgres/data-access')).pgGetEmployees({ page: 1, pageSize: 5000 })).items || []) as Employee[])
        .find((entry) => entry.id === user.id);

  if (!employee) {
    return (
        <DashboardLayout>
            <div className="text-center">
                <h1 className="text-2xl font-bold">{tGlobal.error}</h1>
                <p>{tGlobal.employeeNotFound}</p>
            </div>
        </DashboardLayout>
    );
  }

  const today = new Date();
  const todayString = today.toISOString().split('T')[0];
  const todaysAttendance = employee.attendance.find(a => a.date === todayString);
    const resolvedSearchParams = await searchParams;
  
    const year = resolvedSearchParams?.year ? parseInt(resolvedSearchParams.year) : today.getFullYear();
    const month = resolvedSearchParams?.month ? parseInt(resolvedSearchParams.month) - 1 : today.getMonth();
  const selectedDate = new Date(year, month);

  const { total: totalDeductions, records: deductionRecords } = getMonthlyDeductions(employee, month, year);
  const { total: totalBonuses, records: bonusRecords } = getMonthlyBonuses(employee, month, year);
  
  // Separate advances from actual bonuses for UI display
  const advanceRecords = bonusRecords.filter(r => r.description.startsWith('Approved Advance:'));
  const actualBonusRecords = bonusRecords.filter(r => !r.description.startsWith('Approved Advance:'));
  const totalAdvances = advanceRecords.reduce((sum, rec) => sum + rec.amount, 0);
  const totalActualBonuses = actualBonusRecords.reduce((sum, rec) => sum + rec.amount, 0);

  const netSalary = getNetSalary(employee, month, year);
    const currencySymbol = await getCurrencySymbolAsync();
    const formatAmount = (amount: number) => formatCurrencyUtil(amount, currencySymbol);

  return (
    <DashboardLayout>
      <div className="w-full max-w-7xl mx-auto">
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
          <AttendanceCard todaysAttendance={todaysAttendance} t={tAttendanceCard} />
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">{tEmployeeDashboard.myProfile}</CardTitle>
              <Briefcase className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
                            <div className="text-2xl font-bold">{employee.businessRole || '-'}</div>
              <p className="text-xs text-muted-foreground">{tEmployeeDashboard.myProfileDesc}</p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">{tEmployeeDashboard.assignedShift}</CardTitle>
              <Clock className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold capitalize">{employee.defaultShift}</div>
              <p className="text-xs text-muted-foreground">{tEmployeeDashboard.assignedShiftDesc}</p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">{tEmployeeDashboard.employmentStatus}</CardTitle>
              <UserCheck className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
                <Badge variant={employee.status === "permanent" ? "secondary" : "outline"} className={`text-lg font-bold ${employee.status === 'permanent' ? 'bg-blue-100 text-blue-800' : 'bg-yellow-100 text-yellow-800'}`}>
                  {employee.status}
                </Badge>
              <p className="text-xs text-muted-foreground mt-2">{tEmployeeDashboard.employmentStatusDesc}</p>
            </CardContent>
          </Card>
        </div>
        <div className="mt-8">
          <Card>
              <CardHeader>
                <div className="flex justify-between items-start">
                    <div>
                        <CardTitle>{tEmployeeDashboard.payStubTitle.replace('{monthName}', format(selectedDate, 'MMMM yyyy'))}</CardTitle>
                        <CardDescription>{tEmployeeDashboard.payStubDesc}</CardDescription>
                    </div>
                    <MonthYearPicker initialDate={selectedDate} basePath="/employee/dashboard" />
                </div>
              </CardHeader>
              <CardContent>
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                      <div className="p-4 rounded-lg bg-red-50 border border-red-200">
                          <div className="flex items-center gap-2 text-red-800">
                              <TrendingDown className="h-5 w-5" />
                              <h3 className="font-semibold text-sm">{tEmployeeDashboard.totalDeductions}</h3>
                          </div>
                          <p className="text-2xl font-bold text-red-900 mt-2">{formatAmount(totalDeductions)}</p>
                      </div>
                      <div className="p-4 rounded-lg bg-green-50 border border-green-200">
                          <div className="flex items-center gap-2 text-green-800">
                              <TrendingUp className="h-5 w-5" />
                              <h3 className="font-semibold text-sm">{tEmployeeDashboard.totalBonuses}</h3>
                          </div>
                          <p className="text-2xl font-bold text-green-900 mt-2">{formatAmount(totalActualBonuses)}</p>
                      </div>
                      <div className="p-4 rounded-lg bg-yellow-50 border border-yellow-200">
                          <div className="flex items-center gap-2 text-yellow-800">
                              <DollarSign className="h-5 w-5" />
                              <h3 className="font-semibold text-sm">{tEmployeeDashboard.totalAdvances}</h3>
                          </div>
                          <p className="text-2xl font-bold text-yellow-900 mt-2">{formatAmount(totalAdvances)}</p>
                      </div>
                      <div className="p-4 rounded-lg bg-blue-50 border border-blue-200">
                          <div className="flex items-center gap-2 text-blue-800">
                              <Wallet className="h-5 w-5" />
                              <h3 className="font-semibold text-sm">{tEmployeeDashboard.netSalary}</h3>
                          </div>
                          <p className="text-2xl font-bold text-blue-900 mt-2">{formatAmount(netSalary)}</p>
                      </div>
                  </div>
              </CardContent>
          </Card>
        </div>

        <div className="mt-8 grid gap-8 md:grid-cols-2">
            {deductionRecords.length > 0 && (
                <Card>
                    <CardHeader>
                        <CardTitle>{tEmployeeDashboard.deductionDetails}</CardTitle>
                    </CardHeader>
                    <CardContent>
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead>{tEmployeeDashboard.tableDescription}</TableHead>
                                    <TableHead className="text-right">{tEmployeeDashboard.tableAmount}</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {deductionRecords.map((rec, i) => (
                                    <TableRow key={`ded-${i}`}>
                                        <TableCell>{rec.description}</TableCell>
                                        <TableCell className="text-right">{formatAmount(rec.amount)}</TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </CardContent>
                </Card>
            )}

            {actualBonusRecords.length > 0 && (
                 <Card>
                    <CardHeader>
                        <CardTitle>{tEmployeeDashboard.bonusDetails}</CardTitle>
                    </CardHeader>
                    <CardContent>
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead>{tEmployeeDashboard.tableDescription}</TableHead>
                                    <TableHead className="text-right">{tEmployeeDashboard.tableAmount}</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {actualBonusRecords.map((rec, i) => (
                                    <TableRow key={`bon-${i}`}>
                                        <TableCell>{rec.description}</TableCell>
                                        <TableCell className="text-right">{formatAmount(rec.amount)}</TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </CardContent>
                </Card>
            )}
            
            {advanceRecords.length > 0 && (
                 <Card>
                    <CardHeader>
                        <CardTitle>{tEmployeeDashboard.advanceDetails}</CardTitle>
                    </CardHeader>
                    <CardContent>
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead>{tEmployeeDashboard.tableDescription}</TableHead>
                                    <TableHead className="text-right">{tEmployeeDashboard.tableAmount}</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {advanceRecords.map((rec, i) => (
                                    <TableRow key={`adv-${i}`}>
                                        <TableCell>{rec.description}</TableCell>
                                        <TableCell className="text-right">{formatAmount(rec.amount)}</TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </CardContent>
                </Card>
            )}
        </div>

      </div>
    </DashboardLayout>
  );
}
