'use client';

import React, { useState, useEffect, useMemo } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { ChevronsLeft, Phone, User, Briefcase, FileText } from 'lucide-react';
import { format, startOfMonth, endOfMonth } from 'date-fns';

import { getMockEmployees, getMockOrders, getOtherExpenses, type Employee, type Order, type Expense } from '@/lib/data';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { PageHeader } from '@/components/page-header';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';

export default function EmployeeProfilePage() {
  const router = useRouter();
  const params = useParams();
  const { id } = params;

  const [employee, setEmployee] = useState<Employee | null>(null);
  const [allOrders, setAllOrders] = useState<Order[]>([]);
  const [allExpenses, setAllExpenses] = useState<Expense[]>([]);

  useEffect(() => {
    if (typeof id !== 'string') return;

    const allEmployees = getMockEmployees();
    const foundEmployee = allEmployees.find(e => e.id === id) || null;
    setEmployee(foundEmployee);
    
    const ordersData = getMockOrders();
    const expensesData = getOtherExpenses();
    setAllOrders(ordersData);
    setAllExpenses(expensesData);

  }, [id]);
  
  const { completedOrders, advances, totalEarned, totalAdvanced, currentBalance } = useMemo(() => {
    if (!employee) {
      return { completedOrders: [], advances: [], totalEarned: 0, totalAdvanced: 0, currentBalance: 0 };
    }

    const monthStart = startOfMonth(new Date());
    const monthEnd = endOfMonth(new Date());

    const employeeOrders = allOrders.filter(order =>
      order.artisan === employee.name &&
      order.artisanCompletedDate &&
      new Date(order.artisanCompletedDate) >= monthStart &&
      new Date(order.artisanCompletedDate) <= monthEnd
    );

    const employeeAdvances = allExpenses.filter(exp =>
      exp.person === employee.name &&
      exp.category === 'Salary Advance' &&
      new Date(exp.date) >= monthStart &&
      new Date(exp.date) <= monthEnd
    );

    const earned = employee.role === 'Tailor'
      ? employeeOrders.reduce((sum, order) => sum + (order.totalArtisanWage || 0), 0)
      : employee.monthlySalary || 0;

    const advanced = employeeAdvances.reduce((sum, exp) => sum + exp.amount, 0);

    return {
      completedOrders: employeeOrders,
      advances: employeeAdvances,
      totalEarned: earned,
      totalAdvanced: advanced,
      currentBalance: earned - advanced,
    };
  }, [employee, allOrders, allExpenses]);


  if (!employee) {
    return (
      <div className="flex justify-center items-center h-full">
        <p>Employee not found.</p>
        <Button onClick={() => router.push('/dashboard/employees')} className="mt-4 ml-4">
            Go Back
        </Button>
      </div>
    );
  }

  return (
    <div className="flex flex-col gap-4">
      <PageHeader title={`${employee.name}'s Profile`}>
        <Button variant="outline" onClick={() => router.push('/dashboard/employees')}>
          <ChevronsLeft className="mr-2 h-4 w-4" />
          Back to Employees
        </Button>
      </PageHeader>
      
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
         <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">Monthly Earnings</CardTitle>
                <FileText className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
                <div className="text-2xl font-bold">৳{totalEarned.toFixed(2)}</div>
                <p className="text-xs text-muted-foreground">
                    {employee.role === 'Tailor' ? `from ${completedOrders.length} completed orders this month` : `Fixed salary for ${format(new Date(), 'MMMM')}`}
                </p>
            </CardContent>
        </Card>
         <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">Advance Paid</CardTitle>
                <FileText className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
                <div className="text-2xl font-bold text-red-600">৳{totalAdvanced.toFixed(2)}</div>
                <p className="text-xs text-muted-foreground">Total advance taken this month</p>
            </CardContent>
        </Card>
        <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">Current Balance</CardTitle>
                <FileText className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
                <div className={`text-2xl font-bold ${currentBalance >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                    ৳{currentBalance.toFixed(2)}
                </div>
                <p className="text-xs text-muted-foreground">Net payable/receivable for this month</p>
            </CardContent>
        </Card>
      </div>

      <div className="grid gap-4 md:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle>Personal Information</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center">
              <User className="h-5 w-5 mr-3 text-muted-foreground" />
              <span>{employee.name}</span>
            </div>
            <div className="flex items-center">
              <Phone className="h-5 w-5 mr-3 text-muted-foreground" />
              <span>{employee.phone}</span>
            </div>
            <div className="flex items-center">
              <Briefcase className="h-5 w-5 mr-3 text-muted-foreground" />
              <span>{employee.role}</span>
            </div>
             {employee.monthlySalary && (
                <div className="flex items-center">
                    <FileText className="h-5 w-5 mr-3 text-muted-foreground" />
                    <span>Salary: ৳{employee.monthlySalary.toFixed(2)}</span>
                </div>
            )}
          </CardContent>
        </Card>

        {employee.role === 'Tailor' && (
          <Card>
            <CardHeader>
              <CardTitle>Completed Orders This Month</CardTitle>
              <CardDescription>
                Orders completed in {format(new Date(), 'MMMM yyyy')}
              </CardDescription>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Order ID</TableHead>
                    <TableHead>Item</TableHead>
                    <TableHead className="text-right">Wage</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {completedOrders.length > 0 ? completedOrders.map(order => (
                    <TableRow key={order.id}>
                      <TableCell>{order.id}</TableCell>
                      <TableCell>{order.items.map(i => i.name).join(', ')}</TableCell>
                      <TableCell className="text-right">৳{(order.totalArtisanWage || 0).toFixed(2)}</TableCell>
                    </TableRow>
                  )) : (
                    <TableRow>
                      <TableCell colSpan={3} className="text-center">No orders completed this month.</TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        )}
        
         <Card className={employee.role !== 'Tailor' ? 'md:col-span-1' : ''}>
            <CardHeader>
              <CardTitle>Salary Advances This Month</CardTitle>
               <CardDescription>
                Advances taken in {format(new Date(), 'MMMM yyyy')}
              </CardDescription>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Date</TableHead>
                    <TableHead>Description</TableHead>
                    <TableHead className="text-right">Amount</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {advances.length > 0 ? advances.map(exp => (
                    <TableRow key={exp.id}>
                      <TableCell>{format(new Date(exp.date), 'dd MMM yyyy')}</TableCell>
                      <TableCell>{exp.description}</TableCell>
                      <TableCell className="text-right text-red-600">-৳{exp.amount.toFixed(2)}</TableCell>
                    </TableRow>
                  )) : (
                    <TableRow>
                      <TableCell colSpan={3} className="text-center">No advances taken this month.</TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
      </div>
    </div>
  );
}
