'use client';

import { useState, useEffect, useRef, useMemo } from 'react';
import { useSession } from 'next-auth/react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { DatePicker } from '@/components/ui/date-picker';
import { Textarea } from '@/components/ui/textarea';
import { Progress } from '@/components/ui/progress';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { useToast } from '@/hooks/use-toast';
import {
  Calendar,
  Clock,
  FileText,
  Plus,
  Edit,
  Trash2,
  Check,
  X,
  Search,
  Filter,
  User as UserIcon,
  Upload,
  FileSpreadsheet,
  AlertCircle,
  RefreshCw
} from 'lucide-react';
import { formatDate } from '@/lib/date-utils';
import { AppSpinner } from '@/components/ui/app-loader';
import { MetricStripSkeleton, TableSkeleton } from '@/components/ui/loading-skeletons';
import { FilterSelect } from '@/components/ui/filter-select';
import { TablePagination } from '@/components/ui/table-pagination';
import * as XLSX from 'xlsx';
import { api } from '@/lib/store/api';
import { apiCall, apiErrorMessage } from '@/lib/store/api-call';

interface ItWorkHistoryItem {
  id: string;
  userId: string;
  ticketDate: string;
  ticketType: string;
  subject: string;
  message: string | null;
  responseBy: string | null;
  response: string | null;
  status: string;
  requesterName: string | null;
  createdAt: string;
  updatedAt: string;
}

interface ItWorkHistoryProps {
  userId: string;
  userName: string;
  dateFrom?: string;
  dateTo?: string;
}

interface ImportResult {
  total: number;
  successful: number;
  failed: number;
  successRate: string;
  errors?: string[];
}

export function ItWorkHistory({ userId, userName, dateFrom, dateTo }: ItWorkHistoryProps) {
  const { data: session } = useSession();
  const { toast } = useToast();
  const [workHistory, setWorkHistory] = useState<ItWorkHistoryItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [isAdding, setIsAdding] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [isImporting, setIsImporting] = useState(false);
  const [importProgress, setImportProgress] = useState(0);
  const [isDeleting, setIsDeleting] = useState(false);
  const [importResult, setImportResult] = useState<ImportResult | null>(null);
  const [dragActive, setDragActive] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [entriesPerPage] = useState(10);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Form state
  const [formData, setFormData] = useState({
    ticketDate: '',
    ticketType: 'Network',
    subject: '',
    message: '',
    responseBy: '',
    response: '',
    status: 'Completed',
    requesterName: ''
  });

  const canEdit = session?.user?.role === 'SUPER_ADMIN' || 
    session?.user?.position?.includes('HR') ||
    session?.user?.position?.includes('Manager') ||
    session?.user?.role === 'MANAGER' ||
    session?.user?.role === 'UNIT_LEAD';

  useEffect(() => {
    fetchWorkHistory();
  }, [userId, dateFrom, dateTo]);

  const fetchWorkHistory = async () => {
    try {
      setLoading(true);
      const data = await apiCall<any>(
        api.endpoints.getItWorkHistory.initiate({
          userId,
          startDate: dateFrom,
          endDate: dateTo,
        }),
      );
      setWorkHistory(data);
    } catch (error) {
      console.error('Error fetching work history:', error);
      toast({
        title: 'Error',
        description: 'Failed to load work history',
        variant: 'destructive'
      });
    } finally {
      setLoading(false);
    }
  };

  const handleAdd = () => {
    setIsAdding(true);
    setFormData({
      ticketDate: new Date().toISOString().split('T')[0],
      ticketType: 'Network',
      subject: '',
      message: '',
      responseBy: session?.user?.name || '',
      response: '',
      status: 'Completed',
      requesterName: ''
    });
  };

  const handleCancel = () => {
    setIsAdding(false);
    setEditingId(null);
    setFormData({
      ticketDate: '',
      ticketType: 'Network',
      subject: '',
      message: '',
      responseBy: '',
      response: '',
      status: 'Completed',
      requesterName: ''
    });
  };

  const handleSave = async () => {
    try {
      if (!formData.ticketDate || !formData.subject) {
        toast({
          title: 'Validation Error',
          description: 'Ticket date and subject are required',
          variant: 'destructive'
        });
        return;
      }

      const body = {
        ...(editingId && { id: editingId }),
        userId,
        ...formData
      };

      await apiCall(
        api.endpoints.saveItWorkHistory.initiate({
          method: editingId ? 'PUT' : 'POST',
          body,
        }),
      );

      toast({
        title: 'Success',
        description: editingId ? 'Work history updated successfully' : 'Work history added successfully'
      });

      handleCancel();
      fetchWorkHistory();
    } catch (error: any) {
      console.error('Error saving work history:', error);
      toast({
        title: 'Error',
        description: apiErrorMessage(error, 'Failed to save work history'),
        variant: 'destructive'
      });
    }
  };

  const handleEdit = (item: ItWorkHistoryItem) => {
    setEditingId(item.id);
    setFormData({
      ticketDate: new Date(item.ticketDate).toISOString().split('T')[0],
      ticketType: item.ticketType,
      subject: item.subject,
      message: item.message || '',
      responseBy: item.responseBy || '',
      response: item.response || '',
      status: item.status,
      requesterName: item.requesterName || ''
    });
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Are you sure you want to delete this work history entry?')) {
      return;
    }

    try {
      await apiCall(api.endpoints.deleteItWorkHistory.initiate(id));

      toast({
        title: 'Success',
        description: 'Work history deleted successfully'
      });

      fetchWorkHistory();
    } catch (error) {
      console.error('Error deleting work history:', error);
      toast({
        title: 'Error',
        description: 'Failed to delete work history',
        variant: 'destructive'
      });
    }
  };

  const handleDeleteAll = async () => {
    if (!confirm(`Are you sure you want to delete ALL work history entries for ${userName}? This action cannot be undone.`)) {
      return;
    }

    try {
      setIsDeleting(true);
      await apiCall(api.endpoints.deleteAllItWorkHistory.initiate(userId));

      toast({
        title: 'Success',
        description: 'All work history entries deleted successfully'
      });

      fetchWorkHistory();
    } catch (error: any) {
      console.error('Error deleting all work history:', error);
      toast({
        title: 'Error',
        description: apiErrorMessage(error, 'Failed to delete all work history'),
        variant: 'destructive'
      });
    } finally {
      setIsDeleting(false);
    }
  };

  // Helper function to parse date from DD/MM/YYYY format
  const parseDate = (dateString: string): Date | null => {
    if (!dateString) return null;
    const [day, month, year] = dateString.split('/');
    if (!day || !month || !year) return null;
    return new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
  };

  const handleFileImport = async (file: File) => {
    // Prevent any default behavior and check if already importing
    if (isImporting) {
      return; // Already importing, ignore
    }

    try {
      setIsImporting(true);
      setImportProgress(0);
      setImportResult(null);
      
      // Scroll to import section to show progress
      setTimeout(() => {
        const importSection = document.querySelector('[data-import-section]');
        if (importSection) {
          importSection.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
      }, 100);

      const fileExtension = file.name.split('.').pop()?.toLowerCase();
      
      let records: any[] = [];

      if (fileExtension === 'csv') {
        // Read CSV file
        const text = await file.text();
        
        // Use PapaParse-like simple CSV parser that handles quoted fields
        const parseCSVLine = (line: string): string[] => {
          const result: string[] = [];
          let current = '';
          let inQuotes = false;
          
          for (let i = 0; i < line.length; i++) {
            const char = line[i];
            const nextChar = line[i + 1];
            
            if (char === '"') {
              if (inQuotes && nextChar === '"') {
                // Escaped quote
                current += '"';
                i++; // Skip next quote
              } else {
                // Toggle quote state
                inQuotes = !inQuotes;
              }
            } else if (char === ',' && !inQuotes) {
              // Field separator
              result.push(current.trim());
              current = '';
            } else {
              current += char;
            }
          }
          result.push(current.trim()); // Add last field
          return result;
        };

        const lines = text.split('\n').filter(line => line.trim());
        
        if (lines.length < 2) {
          throw new Error('CSV file is empty or invalid');
        }

        // Parse header
        const headers = parseCSVLine(lines[0]);
        
        // Parse data rows
        for (let i = 1; i < lines.length; i++) {
          const values = parseCSVLine(lines[i]);
          const record: any = {};
          headers.forEach((header, index) => {
            record[header] = (values[index] || '').replace(/^"|"$/g, ''); // Remove surrounding quotes
          });
          if (record['Ticket Date'] || record['Ticket Subject']) {
            records.push(record);
          }
        }
      } else if (fileExtension === 'xlsx' || fileExtension === 'xls') {
        // Read Excel file
        const arrayBuffer = await file.arrayBuffer();
        const workbook = XLSX.read(arrayBuffer, { type: 'array' });
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];
        records = XLSX.utils.sheet_to_json(worksheet);
      } else {
        throw new Error('Unsupported file format. Please upload CSV or Excel file.');
      }

      if (records.length === 0) {
        throw new Error('No records found in the file');
      }

      console.log(`📊 Found ${records.length} records to import`);

      // Set initial progress
      setImportProgress(20);

      // Parse and prepare records for bulk import
      const preparedRecords = [];
      const errors: string[] = [];

      for (let i = 0; i < records.length; i++) {
        const record = records[i];
        const progress = Math.min(70, 20 + Math.round((i / records.length) * 50));
        setImportProgress(progress);

        try {
          const requesterName = record['Name']?.trim() || '';
          const ticketDate = parseDate(record['Ticket Date']?.trim() || '');
          const subject = record['Ticket Subject']?.trim() || '';
          const message = record['Ticket Message']?.trim() || '';
          const responseBy = record['Response By']?.trim() || session?.user?.name || '';
          const responseText = record['Response']?.trim() || '';
          const status = record['Status']?.trim() || 'Completed';
          const ticketType = record['Ticket Type']?.trim() || 'Network';

          if (!ticketDate || !subject) {
            errors.push(`Row ${i + 2}: Missing ticket date or subject`);
            continue;
          }

          preparedRecords.push({
            ticketDate: ticketDate.toISOString(),
            ticketType,
            subject,
            message: message || null,
            responseBy: responseBy || null,
            response: responseText || null,
            status,
            requesterName: requesterName || null
          });
        } catch (error: any) {
          errors.push(`Row ${i + 2}: ${error.message || 'Unknown error'}`);
        }
      }

      // Bulk import all records at once
      setImportProgress(80);
      const result = await apiCall<any>(
        api.endpoints.bulkItWorkHistory.initiate({
          userId,
          records: preparedRecords
        }),
      );
      setImportProgress(100);

      setImportResult({
        total: result.total,
        successful: result.successful,
        failed: result.failed + errors.length,
        successRate: result.successRate,
        errors: [...errors, ...(result.errors || [])].slice(0, 10) // Show first 10 errors
      });

      toast({
        title: 'Import Complete',
        description: `Imported ${result.successful} of ${result.total} records successfully`,
        variant: result.failed === 0 ? 'default' : 'destructive'
      });

      // Refresh work history
      await fetchWorkHistory();
    } catch (error: any) {
      console.error('Error importing file:', error);
      toast({
        title: 'Import Failed',
        description: error.message || 'Failed to import file',
        variant: 'destructive'
      });
    } finally {
      setIsImporting(false);
      setImportProgress(0);
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    }
  };

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    e.preventDefault();
    e.stopPropagation();
    const file = e.target.files?.[0];
    if (file) {
      handleFileImport(file);
    }
  };

  const handleDrag = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === 'dragenter' || e.type === 'dragover') {
      setDragActive(true);
    } else if (e.type === 'dragleave') {
      setDragActive(false);
    }
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);

    const file = e.dataTransfer.files?.[0];
    if (file) {
      handleFileImport(file);
    }
  };

  const filteredHistory = useMemo(() => {
    const result = workHistory.filter(item => {
      const matchesSearch = 
        item.subject.toLowerCase().includes(searchTerm.toLowerCase()) ||
        item.message?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        item.response?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        item.requesterName?.toLowerCase().includes(searchTerm.toLowerCase());
      
      const matchesStatus = statusFilter === 'all' || item.status === statusFilter;

      return matchesSearch && matchesStatus;
    });
    setCurrentPage(1);
    return result;
  }, [workHistory, searchTerm, statusFilter]);

  const paginatedHistory = filteredHistory.slice(
    (currentPage - 1) * entriesPerPage,
    currentPage * entriesPerPage
  );

  // Calculate Stats and KPIs
  const stats = useMemo(() => {
    const total = workHistory.length;
    const byStatus = workHistory.reduce((acc, item) => {
      const status = item.status || 'Unknown';
      acc[status] = (acc[status] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);
    
    const byType = workHistory.reduce((acc, item) => {
      const type = item.ticketType || 'Unknown';
      acc[type] = (acc[type] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);

    // Group by month
    const byMonth = workHistory.reduce((acc, item) => {
      const date = new Date(item.ticketDate);
      const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
      acc[monthKey] = (acc[monthKey] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);

    const completed = byStatus['Completed'] || 0;
    const inProgress = (byStatus['In Progress'] || 0) + (byStatus['Pending'] || 0);
    const cancelled = byStatus['Cancelled'] || 0;
    const completionRate = total > 0 ? ((completed / total) * 100).toFixed(1) : '0';

    // Recent activity (last 30 days)
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
    const recentActivity = workHistory.filter(item => new Date(item.ticketDate) >= thirtyDaysAgo).length;

    return {
      total,
      completed,
      inProgress,
      cancelled,
      completionRate,
      byStatus,
      byType,
      byMonth,
      recentActivity
    };
  }, [workHistory]);

  const getStatusBadgeColor = (status: string) => {
    switch (status.toLowerCase()) {
      case 'completed':
        return 'bg-green-100 dark:bg-green-950/50 text-green-800 dark:text-green-300 border-green-200 dark:border-green-800';
      case 'in progress':
      case 'pending':
        return 'bg-yellow-100 dark:bg-yellow-950/50 text-yellow-800 dark:text-yellow-300 border-yellow-200 dark:border-yellow-800';
      case 'cancelled':
        return 'bg-red-100 dark:bg-red-950/50 text-red-800 dark:text-red-300 border-red-200 dark:border-red-800';
      default:
        return 'bg-muted text-foreground border-border';
    }
  };

  if (loading) {
    return (
      <div className="space-y-4" aria-busy aria-label="Loading work history">
        <MetricStripSkeleton cells={6} />
        <TableSkeleton rows={5} cols={5} />
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* Stats and KPIs Section */}
      {workHistory.length > 0 && (
        <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
          <Card className="p-4 rounded-xl border border-border bg-card bg-gradient-to-br from-primary/10 to-primary/15 border-primary/20">
            <div className="text-center">
              <div className="text-2xl font-bold text-primary">{stats.total}</div>
              <div className="text-xs text-primary mt-1">Total Tickets</div>
            </div>
          </Card>
          <Card className="p-4 rounded-xl border border-border bg-card bg-gradient-to-br from-green-50 to-green-100 dark:from-green-950/30 dark:to-green-950/50 border-green-200 dark:border-green-900/50">
            <div className="text-center">
              <div className="text-2xl font-bold text-green-700 dark:text-green-300">{stats.completed}</div>
              <div className="text-xs text-green-600 dark:text-green-400 mt-1">Completed</div>
            </div>
          </Card>
          <Card className="p-4 rounded-xl border border-border bg-card bg-gradient-to-br from-yellow-50 to-yellow-100 dark:from-yellow-950/30 dark:to-yellow-950/50 border-yellow-200 dark:border-yellow-900/50">
            <div className="text-center">
              <div className="text-2xl font-bold text-yellow-700 dark:text-yellow-300">{stats.inProgress}</div>
              <div className="text-xs text-yellow-600 dark:text-yellow-400 mt-1">In Progress</div>
            </div>
          </Card>
          <Card className="p-4 rounded-xl border border-border bg-card bg-gradient-to-br from-primary/5 to-primary/10 dark:from-primary/10 dark:to-primary/20 border-primary/20 dark:border-primary/30">
            <div className="text-center">
              <div className="text-2xl font-bold text-primary">{stats.completionRate}%</div>
              <div className="text-xs text-primary mt-1">Completion Rate</div>
            </div>
          </Card>
          <Card className="p-4 rounded-xl border border-border bg-card bg-gradient-to-br from-teal-50 to-teal-100 dark:from-teal-950/30 dark:to-teal-950/50 border-teal-200 dark:border-teal-900/50">
            <div className="text-center">
              <div className="text-2xl font-bold text-teal-700 dark:text-teal-300">{stats.recentActivity}</div>
              <div className="text-xs text-teal-600 dark:text-teal-400 mt-1">Last 30 Days</div>
            </div>
          </Card>
          <Card className="p-4 rounded-xl border border-border bg-card bg-gradient-to-br from-orange-50 to-orange-100 dark:from-orange-950/30 dark:to-orange-950/50 border-orange-200 dark:border-orange-900/50">
            <div className="text-center">
              <div className="text-2xl font-bold text-orange-700 dark:text-orange-300">{Object.keys(stats.byType).length}</div>
              <div className="text-xs text-orange-600 dark:text-orange-400 mt-1">Ticket Types</div>
            </div>
          </Card>
        </div>
      )}

      <Card className="rounded-xl border border-border bg-card overflow-hidden">
        <div className="flex items-center justify-between px-5 py-4 border-b border-border bg-muted/30">
          <div>
            <h2 className="text-xl font-bold text-foreground">IT Work History</h2>
            <p className="text-xs text-muted-foreground mt-0.5">
              {userName} • {workHistory.length} total entries
            </p>
          </div>
          <div className="flex gap-2">
            {canEdit && (
              <>
                <Button onClick={handleAdd} size="sm" className="bg-primary hover:bg-primary">
                  <Plus className="h-3.5 w-3.5 mr-1.5" />
                  Add
                </Button>
                {workHistory.length > 0 && (
                  <Button 
                    onClick={handleDeleteAll} 
                    size="sm"
                    variant="destructive"
                    disabled={isDeleting}
                  >
                    {isDeleting ? (
                      <AppSpinner className="mr-1.5 h-3.5 w-3.5" />
                    ) : (
                      <Trash2 className="h-3.5 w-3.5 mr-1.5" />
                    )}
                    Delete All
                  </Button>
                )}
              </>
            )}
          </div>
        </div>

        <div className="p-4">
        {/* Import Section */}
        {canEdit && (
          <Card 
            data-import-section
            className={`p-4 mb-4 border border-primary/20 transition-all ${
              isImporting ? 'bg-primary/15 border-primary/40 shadow-lg' : 'bg-primary/5'
            }`}
          >
            <div className="space-y-3">
              <div className="flex items-center gap-2">
                <FileSpreadsheet className={`h-4 w-4 text-primary ${isImporting ? 'animate-pulse' : ''}`} />
                <h3 className="text-sm font-semibold text-foreground">
                  Bulk Import {isImporting && '(Processing...)'}
                </h3>
              </div>
              
              <Alert className="py-2">
                <AlertCircle className="h-3.5 w-3.5" />
                <AlertDescription className="text-xs">
                  <strong>CSV Format:</strong> Name, Ticket Type, Ticket Date (DD/MM/YYYY), Ticket Subject, Ticket Message, Response By, Response, Status
                </AlertDescription>
              </Alert>

              <div
                className={`border border-dashed rounded-lg p-4 text-center transition-colors ${
                  isImporting
                    ? 'border-border bg-muted cursor-not-allowed opacity-60'
                    : dragActive
                    ? 'border-blue-500 bg-primary/15'
                    : 'border-border bg-card hover:border-primary/40 hover:bg-primary/5'
                }`}
                onDragEnter={isImporting ? undefined : handleDrag}
                onDragLeave={isImporting ? undefined : handleDrag}
                onDragOver={isImporting ? undefined : handleDrag}
                onDrop={isImporting ? undefined : handleDrop}
              >
                <input
                  ref={fileInputRef}
                  type="file"
                  accept=".csv,.xlsx,.xls"
                  onChange={handleFileSelect}
                  onClick={(e) => {
                    // Reset value to allow selecting the same file again
                    e.currentTarget.value = '';
                  }}
                  className="hidden"
                  disabled={isImporting}
                />
                
                {isImporting ? (
                  <div className="space-y-3 py-2">
                    <div className="flex justify-center py-1">
                      <AppSpinner className="h-8 w-8 border-[3px] text-primary" />
                    </div>
                    <div className="space-y-2">
                      <div className="flex items-center justify-between text-sm">
                        <span className="font-semibold text-foreground">
                          {importProgress < 20 && "📖 Reading file..."}
                          {importProgress >= 20 && importProgress < 80 && "⚙️ Processing data..."}
                          {importProgress >= 80 && importProgress < 100 && "💾 Importing to database..."}
                          {importProgress === 100 && "✅ Complete!"}
                        </span>
                        <span className="text-primary font-bold text-sm">{importProgress}%</span>
                      </div>
                      <Progress value={importProgress} className="w-full h-2" />
                      <p className="text-xs text-center text-muted-foreground">
                        Please wait, do not close this page...
                      </p>
                    </div>
                  </div>
                ) : (
                  <div className="space-y-2">
                    <Upload className="h-8 w-8 text-muted-foreground mx-auto" />
                    <div>
                      <p className="text-xs text-muted-foreground mb-1.5">
                        Drag & drop or
                      </p>
                      <Button
                        type="button"
                        onClick={(e) => {
                          e.preventDefault();
                          e.stopPropagation();
                          fileInputRef.current?.click();
                        }}
                        size="sm"
                        variant="outline"
                        className="bg-card text-xs"
                        disabled={isImporting}
                      >
                        <FileSpreadsheet className="h-3 w-3 mr-1.5" />
                        Browse
                      </Button>
                    </div>
                    <p className="text-[10px] text-muted-foreground">
                      CSV, XLSX, XLS
                    </p>
                  </div>
                )}
              </div>

              {importResult && !isImporting && (
                <Alert className={importResult.failed > 0 ? 'border-yellow-500 bg-yellow-50' : 'border-green-500 bg-green-50'}>
                  <AlertCircle className={`h-4 w-4 ${importResult.failed > 0 ? 'text-yellow-600' : 'text-green-600'}`} />
                  <AlertDescription>
                    <div className="space-y-2">
                      <p className="text-sm">
                        <strong>Import Summary:</strong> {importResult.successful} successful, {importResult.failed} failed out of {importResult.total} total ({importResult.successRate} success rate)
                      </p>
                      {importResult.errors && importResult.errors.length > 0 && (
                        <div className="mt-2">
                          <p className="text-xs font-medium">Errors:</p>
                          <ul className="text-xs list-disc list-inside space-y-1 max-h-32 overflow-y-auto">
                            {importResult.errors.map((error, index) => (
                              <li key={index}>{error}</li>
                            ))}
                            {importResult.errors.length >= 10 && (
                              <li className="text-muted-foreground">... and more errors</li>
                            )}
                          </ul>
                        </div>
                      )}
                    </div>
                  </AlertDescription>
                </Alert>
              )}
            </div>
          </Card>
        )}

        {/* Search and Filter */}
        <div className="flex gap-2 mb-4">
          <div className="flex-1 relative">
            <Search className="absolute left-2 top-1/2 transform -translate-y-1/2 text-muted-foreground h-3.5 w-3.5" />
            <Input
              placeholder="Search tickets..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-8 h-9 text-sm"
            />
          </div>
          <FilterSelect
            value={statusFilter}
            onValueChange={setStatusFilter}
            placeholder="All Status"
            className="h-9 w-[9.5rem]"
            options={[
              { value: 'all', label: 'All Status' },
              { value: 'Completed', label: 'Completed' },
              { value: 'In Progress', label: 'In Progress' },
              { value: 'Pending', label: 'Pending' },
              { value: 'Cancelled', label: 'Cancelled' },
            ]}
          />
        </div>

        {/* Add/Edit Form */}
        {(isAdding || editingId) && (
          <Card className="p-4 mb-4 border border-primary/20 bg-primary/5">
            <div className="space-y-3">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                <div>
                  <label className="block text-sm font-medium text-foreground/80 mb-1">
                    Ticket Date *
                  </label>
                  <DatePicker
                    value={formData.ticketDate}
                    onChange={(ticketDate) => setFormData({ ...formData, ticketDate })}
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-foreground/80 mb-1">
                    Ticket Type
                  </label>
                  <Input
                    value={formData.ticketType}
                    onChange={(e) => setFormData({ ...formData, ticketType: e.target.value })}
                  />
                </div>
                <div className="md:col-span-2">
                  <label className="block text-sm font-medium text-foreground/80 mb-1">
                    Subject *
                  </label>
                  <Input
                    value={formData.subject}
                    onChange={(e) => setFormData({ ...formData, subject: e.target.value })}
                    placeholder="Enter ticket subject"
                  />
                </div>
                <div className="md:col-span-2">
                  <label className="block text-sm font-medium text-foreground/80 mb-1">
                    Requester Name
                  </label>
                  <Input
                    value={formData.requesterName}
                    onChange={(e) => setFormData({ ...formData, requesterName: e.target.value })}
                    placeholder="Enter requester name"
                  />
                </div>
                <div className="md:col-span-2">
                  <label className="block text-sm font-medium text-foreground/80 mb-1">
                    Message
                  </label>
                  <Textarea
                    value={formData.message}
                    onChange={(e) => setFormData({ ...formData, message: e.target.value })}
                    placeholder="Enter ticket message/description"
                    rows={3}
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-foreground/80 mb-1">
                    Response By
                  </label>
                  <Input
                    value={formData.responseBy}
                    onChange={(e) => setFormData({ ...formData, responseBy: e.target.value })}
                    placeholder="Enter responder name"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-foreground/80 mb-1">
                    Status
                  </label>
                  <FilterSelect
                    value={formData.status}
                    onValueChange={(status) => setFormData({ ...formData, status })}
                    placeholder="Status"
                    className="w-full"
                    options={[
                      { value: 'Completed', label: 'Completed' },
                      { value: 'In Progress', label: 'In Progress' },
                      { value: 'Pending', label: 'Pending' },
                      { value: 'Cancelled', label: 'Cancelled' },
                    ]}
                  />
                </div>
                <div className="md:col-span-2">
                  <label className="block text-sm font-medium text-foreground/80 mb-1">
                    Response
                  </label>
                  <Textarea
                    value={formData.response}
                    onChange={(e) => setFormData({ ...formData, response: e.target.value })}
                    placeholder="Enter response/resolution"
                    rows={3}
                  />
                </div>
              </div>
              <div className="flex justify-end gap-2">
                <Button variant="outline" onClick={handleCancel}>
                  <X className="h-4 w-4 mr-2" />
                  Cancel
                </Button>
                <Button onClick={handleSave} className="bg-primary hover:bg-primary">
                  <Check className="h-4 w-4 mr-2" />
                  Save
                </Button>
              </div>
            </div>
          </Card>
        )}

        {/* Work History List */}
        <div className="space-y-2">
          {filteredHistory.length === 0 ? (
            <div className="text-center py-8 text-muted-foreground">
              <FileText className="h-8 w-8 mx-auto mb-2 text-muted-foreground" />
              <p className="text-sm">No work history entries found</p>
            </div>
          ) : (
            paginatedHistory.map((item) => (
              <Card key={item.id} className="p-3 rounded-xl hover:bg-muted/50 transition-colors border border-border bg-card">
                <div className="flex items-start justify-between gap-3">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1.5 flex-wrap">
                      <h3 className="text-sm font-semibold text-foreground truncate">{item.subject}</h3>
                      <Badge className={`${getStatusBadgeColor(item.status)} text-xs px-1.5 py-0.5`}>
                        {item.status}
                      </Badge>
                    </div>
                    
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-2 text-xs text-muted-foreground mb-2">
                      <div className="flex items-center gap-1">
                        <Calendar className="h-3 w-3" />
                        <span className="truncate">{formatDate(new Date(item.ticketDate), { format: 'short' })}</span>
                      </div>
                      {item.requesterName && (
                        <div className="flex items-center gap-1">
                          <UserIcon className="h-3 w-3" />
                          <span className="truncate">{item.requesterName}</span>
                        </div>
                      )}
                      {item.responseBy && (
                        <div className="flex items-center gap-1">
                          <UserIcon className="h-3 w-3" />
                          <span className="truncate">{item.responseBy}</span>
                        </div>
                      )}
                      <div className="flex items-center gap-1">
                        <FileText className="h-3 w-3" />
                        <span className="truncate">{item.ticketType}</span>
                      </div>
                    </div>

                    {item.message && (
                      <div className="mb-1.5">
                        <p className="text-xs font-medium text-foreground/80 mb-0.5">Message:</p>
                        <p className="text-xs text-muted-foreground bg-muted/50 p-2 rounded line-clamp-2">{item.message}</p>
                      </div>
                    )}

                    {item.response && (
                      <div>
                        <p className="text-xs font-medium text-foreground/80 mb-0.5">Response:</p>
                        <p className="text-xs text-muted-foreground bg-primary/10 p-2 rounded line-clamp-2">{item.response}</p>
                      </div>
                    )}
                  </div>

                  {canEdit && (
                    <div className="flex gap-1 flex-shrink-0">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleEdit(item)}
                        className="h-7 w-7 p-0"
                      >
                        <Edit className="h-3.5 w-3.5" />
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleDelete(item.id)}
                        className="h-7 w-7 p-0 text-red-600 hover:text-red-700 hover:border-red-300"
                      >
                        <Trash2 className="h-3.5 w-3.5" />
                      </Button>
                    </div>
                  )}
                </div>
              </Card>
            ))
          )}
        </div>

        {/* Summary + Pagination */}
        {filteredHistory.length > 0 && (
          <TablePagination
            currentPage={currentPage}
            totalItems={filteredHistory.length}
            pageSize={entriesPerPage}
            onPageChange={setCurrentPage}
            itemLabel="entries"
          />
        )}
        </div>
      </Card>
    </div>
  );
}
