
"use client";

import React, { useState, useEffect, useCallback } from 'react';
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, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { ScrollArea } from '@/components/ui/scroll-area';
import { useToast } from '@/hooks/use-toast';
import { ClipboardX, Pencil, Check, XSquare, Trash2, Loader2 } from 'lucide-react';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";

const LOCAL_STORAGE_KEY_ERROR_RECORDS = 'countErrorTrackerRecords';

interface ErrorRecord {
  id: string;
  location: string;
  counterId: string;
  counterName: string;
  errors: number;
  notes: string;
  timestamp: number;
}

const initialFormData = {
  location: '',
  counterId: '',
  counterName: '',
  errors: 1,
  notes: '',
};

export default function CountErrorTrackerPage() {
  const [formData, setFormData] = useState(initialFormData);
  const [errorRecords, setErrorRecords] = useState<ErrorRecord[]>([]);
  const [editingRecordId, setEditingRecordId] = useState<string | null>(null);
  const [editFormData, setEditFormData] = useState<Partial<Omit<ErrorRecord, 'id' | 'timestamp'>>>({});
  const [isInitialized, setIsInitialized] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const { toast } = useToast();

  const makeId = () => Math.random().toString(36).substring(2, 11);

  // Load records from localStorage
  useEffect(() => {
    try {
      const storedRecords = localStorage.getItem(LOCAL_STORAGE_KEY_ERROR_RECORDS);
      if (storedRecords) {
        const parsedRecords: ErrorRecord[] = JSON.parse(storedRecords);
        parsedRecords.sort((a, b) => b.timestamp - a.timestamp); // Newest first
        setErrorRecords(parsedRecords);
      }
    } catch (error) {
      console.error("Error loading error records from localStorage:", error);
      toast({
        title: "Error Loading Data",
        description: "Could not load saved error records.",
        variant: "destructive",
      });
    }
    setIsInitialized(true);
  }, [toast]);

  // Save records to localStorage
  useEffect(() => {
    if (isInitialized) {
      try {
        localStorage.setItem(LOCAL_STORAGE_KEY_ERROR_RECORDS, JSON.stringify(errorRecords));
      } catch (error) {
        console.error("Error saving error records to localStorage:", error);
        toast({
          title: "Error Saving Data",
          description: "Could not save error records.",
          variant: "destructive",
        });
      }
    }
  }, [errorRecords, isInitialized, toast]);

  const formatCounterId = (id: string): string => {
    return id.replace(/\D/g, '').padStart(8, '0');
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    if (name === "location") {
      setFormData(prev => ({ ...prev, [name]: value.toUpperCase() }));
    } else if (name === "errors") {
      setFormData(prev => ({ ...prev, [name]: parseInt(value, 10) || 1 }));
    } else {
      setFormData(prev => ({ ...prev, [name]: value }));
    }
  };
  
  const handleCounterIdChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    let value = e.target.value.replace(/\D/g, ''); // Allow only digits
    if (value.length > 8) value = value.slice(0, 8); // Max 8 digits
    setFormData(prev => ({ ...prev, counterId: value }));
  };

  const handleEditInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
     if (name === "location") {
      setEditFormData(prev => ({ ...prev, [name]: value.toUpperCase() }));
    } else if (name === "errors") {
      setEditFormData(prev => ({ ...prev, [name]: parseInt(value, 10) || 1 }));
    } else {
      setEditFormData(prev => ({ ...prev, [name]: value }));
    }
  };
  
  const handleEditCounterIdChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    let value = e.target.value.replace(/\D/g, '');
    if (value.length > 8) value = value.slice(0, 8);
    setEditFormData(prev => ({ ...prev, counterId: value }));
  };


  const handleSubmitError = (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.location || !formData.counterId || !formData.counterName || formData.errors < 1) {
      toast({ title: "Missing Information", description: "Please fill all required fields (Location, Counter ID, Counter Name, Errors). Errors must be at least 1.", variant: "destructive" });
      return;
    }
    setIsSubmitting(true);
    // Simulate async operation
    setTimeout(() => {
      const newRecord: ErrorRecord = {
        ...formData,
        id: makeId(),
        counterId: formatCounterId(formData.counterId),
        timestamp: Date.now(),
      };
      setErrorRecords(prev => [newRecord, ...prev]);
      setFormData(initialFormData); // Reset form
      setIsSubmitting(false);
      toast({ title: "Error Report Submitted", description: `Error at location ${newRecord.location} logged.` });
    }, 500);
  };

  const handleStartEdit = (record: ErrorRecord) => {
    setEditingRecordId(record.id);
    setEditFormData({
      location: record.location,
      counterId: record.counterId,
      counterName: record.counterName,
      errors: record.errors,
      notes: record.notes,
    });
  };

  const handleSaveEdit = () => {
    if (!editingRecordId || !editFormData.location || !editFormData.counterId || !editFormData.counterName || (editFormData.errors !== undefined && editFormData.errors < 1)) {
      toast({ title: "Missing Information", description: "Please fill all required fields for editing.", variant: "destructive" });
      return;
    }
    
    const formattedCounterId = formatCounterId(editFormData.counterId || '');

    setErrorRecords(prev =>
      prev.map(record =>
        record.id === editingRecordId
          ? { ...record, ...editFormData, counterId: formattedCounterId, errors: editFormData.errors || 1 }
          : record
      )
    );
    setEditingRecordId(null);
    setEditFormData({});
    toast({ title: "Record Updated", description: "Error record has been updated." });
  };

  const handleCancelEdit = () => {
    setEditingRecordId(null);
    setEditFormData({});
  };

  const handleDeleteRecord = (recordId: string) => {
    setErrorRecords(prev => prev.filter(record => record.id !== recordId));
    toast({ title: "Record Deleted", description: "Error record has been removed." });
  };

  if (!isInitialized) {
    return (
      <div className="container mx-auto px-4 py-12 flex justify-center items-center min-h-[calc(100vh-150px)]">
        <p>Loading error tracker...</p>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8 space-y-8 min-h-[calc(100vh-120px)]">
      <header className="text-center">
        <h1 className="text-3xl md:text-4xl font-bold text-primary flex items-center justify-center gap-2">
          <ClipboardX className="h-8 w-8 md:h-10 md:w-10" /> Count Error Tracker
        </h1>
        <p className="text-muted-foreground mt-1">Track and manage inventory count discrepancies.</p>
      </header>

      <Card className="shadow-xl">
        <CardHeader>
          <CardTitle>Submit New Error Report</CardTitle>
          <CardDescription>Enter details for the count error.</CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmitError} className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <Label htmlFor="location">Location Number</Label>
                <Input
                  id="location"
                  name="location"
                  value={formData.location}
                  onChange={handleInputChange}
                  placeholder="e.g., 25L06 or 176"
                  className="uppercase"
                  required
                />
              </div>
              <div>
                <Label htmlFor="counterId">Counter ID (8 digits)</Label>
                <Input
                  id="counterId"
                  name="counterId"
                  value={formData.counterId}
                  onChange={handleCounterIdChange}
                  placeholder="e.g., 00123456"
                  maxLength={8}
                  pattern="\d*"
                  required
                />
              </div>
            </div>
            <div>
              <Label htmlFor="counterName">Counter Name</Label>
              <Input
                id="counterName"
                name="counterName"
                value={formData.counterName}
                onChange={handleInputChange}
                placeholder="Enter counter's full name"
                required
              />
            </div>
            <div>
              <Label htmlFor="errors">Number of Errors</Label>
              <Input
                id="errors"
                name="errors"
                type="number"
                value={formData.errors}
                onChange={handleInputChange}
                min="1"
                required
                className="w-full"
              />
            </div>
            <div>
              <Label htmlFor="notes">Notes</Label>
              <Textarea
                id="notes"
                name="notes"
                value={formData.notes}
                onChange={handleInputChange}
                rows={4}
                placeholder="Describe the error, items involved, action taken, etc."
              />
            </div>
            <div className="flex justify-end">
              <Button type="submit" disabled={isSubmitting}>
                {isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                Submit Error Report
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>

      <Card className="shadow-xl">
        <CardHeader>
          <CardTitle>Error Records ({errorRecords.length})</CardTitle>
          <CardDescription>List of all logged count errors. Click pencil to edit, X to delete.</CardDescription>
        </CardHeader>
        <CardContent>
          {errorRecords.length === 0 ? (
            <p className="text-muted-foreground text-center py-4">No error records submitted yet.</p>
          ) : (
            <ScrollArea className="max-h-[600px] w-full rounded-md border">
              <Table>
                <TableHeader className="sticky top-0 bg-muted/50 backdrop-blur-sm">
                  <TableRow>
                    <TableHead>Location</TableHead>
                    <TableHead>Counter ID</TableHead>
                    <TableHead>Counter Name</TableHead>
                    <TableHead>Errors</TableHead>
                    <TableHead>Notes</TableHead>
                    <TableHead className="text-right w-[130px]">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {errorRecords.map((record) => (
                    <TableRow key={record.id} className={editingRecordId === record.id ? 'bg-accent/50' : ''}>
                      {editingRecordId === record.id ? (
                        <>
                          <TableCell>
                            <Input name="location" value={editFormData.location || ''} onChange={handleEditInputChange} className="h-8 text-sm uppercase" placeholder="e.g., 25L06 or 176" />
                          </TableCell>
                          <TableCell>
                            <Input name="counterId" value={editFormData.counterId || ''} onChange={handleEditCounterIdChange} className="h-8 text-sm" maxLength={8} pattern="\d*" />
                          </TableCell>
                          <TableCell>
                            <Input name="counterName" value={editFormData.counterName || ''} onChange={handleEditInputChange} className="h-8 text-sm" />
                          </TableCell>
                          <TableCell>
                            <Input name="errors" type="number" value={editFormData.errors || 1} onChange={handleEditInputChange} className="h-8 text-sm w-20" min="1" />
                          </TableCell>
                          <TableCell>
                            <Textarea name="notes" value={editFormData.notes || ''} onChange={handleEditInputChange} rows={1} className="text-sm min-h-[32px]" placeholder="Describe the error, items involved, action taken, etc." />
                          </TableCell>
                          <TableCell className="text-right space-x-1">
                            <Button variant="ghost" size="icon" onClick={handleSaveEdit} aria-label="Save changes">
                              <Check className="h-4 w-4 text-green-600" />
                            </Button>
                            <Button variant="ghost" size="icon" onClick={handleCancelEdit} aria-label="Cancel edit">
                              <XSquare className="h-4 w-4 text-red-600" />
                            </Button>
                          </TableCell>
                        </>
                      ) : (
                        <>
                          <TableCell className="font-medium">{record.location}</TableCell>
                          <TableCell>{record.counterId}</TableCell>
                          <TableCell>{record.counterName}</TableCell>
                          <TableCell>{record.errors}</TableCell>
                          <TableCell className="whitespace-pre-wrap max-w-xs truncate">{record.notes}</TableCell>
                          <TableCell className="text-right space-x-1">
                            <Button variant="ghost" size="icon" onClick={() => handleStartEdit(record)} aria-label="Edit record">
                              <Pencil className="h-4 w-4 text-blue-600" />
                            </Button>
                             <AlertDialog>
                              <AlertDialogTrigger asChild>
                                <Button variant="ghost" size="icon" aria-label="Delete record">
                                  <Trash2 className="h-4 w-4 text-destructive" />
                                </Button>
                              </AlertDialogTrigger>
                              <AlertDialogContent>
                                <AlertDialogHeader>
                                  <AlertDialogTitle>Are you sure?</AlertDialogTitle>
                                  <AlertDialogDescription>
                                    This action will permanently delete this error record. This cannot be undone.
                                  </AlertDialogDescription>
                                </AlertDialogHeader>
                                <AlertDialogFooter>
                                  <AlertDialogCancel>Cancel</AlertDialogCancel>
                                  <AlertDialogAction onClick={() => handleDeleteRecord(record.id)} className="bg-destructive hover:bg-destructive/90">
                                    Yes, delete record
                                  </AlertDialogAction>
                                </AlertDialogFooter>
                              </AlertDialogContent>
                            </AlertDialog>
                          </TableCell>
                        </>
                      )}
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </ScrollArea>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
