
"use client"

import * as React from "react"
import { useParams, useRouter } from "next/navigation"
import Link from "next/link"
import { ArrowLeft, Loader2 } from "lucide-react"

import type { Site, LaborCategory, LaborLog, Laborer } from "@/lib/types"

import { LaborForm, type LaborFormValues } from "@/app/dashboard/labor/labor-form"
import { Button, buttonVariants } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import { useToast } from "@/hooks/use-toast"
import { cn } from "@/lib/utils"
import { getSites } from "@/lib/sites-service"
import { getLaborCategories, getLaborLogById, updateLaborLog, getLaborers } from "@/lib/labor-service"


export default function EditLaborLogPage() {
  const router = useRouter()
  const params = useParams()
  const { toast } = useToast()
  
  const id = Array.isArray(params.id) ? params.id[0] : params.id;

  const [log, setLog] = React.useState<LaborLog | null>(null)
  const [sites, setSites] = React.useState<Site[]>([])
  const [laborers, setLaborers] = React.useState<Laborer[]>([]);
  const [categories, setCategories] = React.useState<LaborCategory[]>([])
  const [loading, setLoading] = React.useState(true)
  const [isSubmitting, setIsSubmitting] = React.useState(false)

  React.useEffect(() => {
    if (!id) return;
    
    let active = true;
    const unsubscribes: (() => void)[] = [];

    const fetchData = async () => {
      setLoading(true);
      try {
        const logData = await getLaborLogById(id);

        if (!active) return;
        
        if (!logData) {
          toast({
            title: "Error",
            description: "Labor log not found.",
            variant: "destructive",
          })
          router.push('/dashboard/labor');
          return;
        }

        setLog(logData);
        
        unsubscribes.push(getSites(sitesData => active && setSites(sitesData)));
        unsubscribes.push(getLaborers(laborerData => active && setLaborers(laborerData)));
        unsubscribes.push(getLaborCategories(categoriesData => active && setCategories(categoriesData)));

      } catch (error) {
        console.error("Failed to fetch data:", error);
        toast({
          title: "Error",
          description: "Failed to load required data. Please try again.",
          variant: "destructive",
        });
      } finally {
        if (active) {
            setLoading(false);
        }
      }
    };
    
    fetchData();

    return () => {
      active = false;
      unsubscribes.forEach(unsub => unsub());
    }
  }, [id, router, toast])

  const handleSubmit = async (values: LaborFormValues) => {
    if (!id || !log) return;
    setIsSubmitting(true);
    
    const isPaymentOnly = (log.items || []).length === 0;

    let updatedLogData: Partial<Omit<LaborLog, 'id'>>;
    
    const laborer = laborers.find(l => l.id === values.laborerId);
    if (!laborer) {
      toast({ title: "Error", description: "Selected laborer not found.", variant: "destructive" });
      setIsSubmitting(false);
      return;
    }

    if (isPaymentOnly) {
      updatedLogData = {
        date: values.date,
        siteId: values.siteId,
        laborerId: values.laborerId,
        laborerName: laborer.name,
        items: [],
        totalCost: 0,
        amountPaid: values.totalAmountPaid,
        balance: 0 - values.totalAmountPaid,
        imageUrl: values.imageUrl,
        description: values.description,
      };
    } else {
      const regularTotal = values.entries?.reduce((acc, entry) => acc + (entry.count * entry.costPerHead), 0) || 0;
      const specialTotal = values.specialEntries?.reduce((acc, entry) => acc + (entry.quantity * entry.costPerHead), 0) || 0;
      const totalCost = regularTotal + specialTotal;
      const balance = totalCost - values.totalAmountPaid;
      
      updatedLogData = {
        date: values.date,
        siteId: values.siteId,
        laborerId: values.laborerId,
        laborerName: laborer.name,
        items: [
          ...(values.entries?.map(e => ({ ...e })) || []),
          ...(values.specialEntries?.map(e => ({ category: 'Special Worker', count: e.quantity, costPerHead: e.costPerHead, description: e.description })) || [])
        ],
        totalCost,
        amountPaid: values.totalAmountPaid,
        balance,
        imageUrl: values.imageUrl,
        description: values.description,
      };
    }


    try {
        await updateLaborLog(id, updatedLogData);
        toast({
            title: "Success",
            description: "Labor entry updated successfully.",
        })
        router.push("/dashboard/labor")
        router.refresh() // To reflect changes on the main page
    } catch (error) {
         console.error("Failed to update labor log:", error);
         toast({
            title: "Error",
            description: "Failed to update labor entry.",
            variant: "destructive",
        })
    } finally {
        setIsSubmitting(false)
    }
  }
  
  const isInitialDataLoading = loading || !log || !sites.length || !laborers.length;


  if (isInitialDataLoading) {
    return (
        <div className="flex justify-center items-center h-64">
            <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
        </div>
    )
  }
  
  const isPaymentOnly = (log.items || []).length === 0;
  const pageTitle = isPaymentOnly ? `Edit Payment for ${log.laborerName}` : `Edit Entry for ${log.laborerName}`


  const headerContent = (
    <div className={cn("flex items-center gap-4")}>
        <Link href="/dashboard/labor" className={cn(buttonVariants({ variant: "outline", size: "icon" }))}>
            <ArrowLeft className="h-4 w-4" />
            <span className="sr-only">Back</span>
        </Link>
        <div>
          <h2 className="text-lg font-semibold leading-none tracking-tight">{pageTitle}</h2>
          <p className="text-sm text-muted-foreground">Log ID: {log.id}</p>
        </div>
    </div>
  );

  return (
    <div className="space-y-6">
       <Card className="p-0 overflow-hidden">
          <LaborForm
              sites={sites}
              laborers={laborers}
              categories={categories}
              initialData={log}
              onSubmit={handleSubmit}
              isSubmitting={isSubmitting}
              submitButtonText="Save Changes"
              header={headerContent}
          />
      </Card>
    </div>
  )
}
