'use client';

import { useState, useEffect, useCallback } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter, useParams } from 'next/navigation';
import { ProtectedLayout } from '@/components/protected-layout';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Checkbox } from '@/components/ui/checkbox';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { useToast } from '@/components/ui/use-toast';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { ArrowLeft, Plus, Minus, FileText, TrendingUp, DollarSign, Users, Calendar, Eye } from 'lucide-react';
import { format } from 'date-fns';

interface CollectionFile {
  id: string;
  customerName: string;
  phoneNumber: string;
  totalToCollect: number;
  outstandingBalance: number;
  status: string;
  assignedAgent: { id: string; name: string; email: string } | null;
}

interface BatchDetail {
  id: string;
  name: string;
  description: string | null;
  clientName: string | null;
  targetAmount: number;
  startDate: string | null;
  endDate: string | null;
  isActive: boolean;
  collectionFiles: CollectionFile[];
  totalToCollect: number;
  totalCollected: number;
  totalOutstanding: number;
  createdAt: string;
}

export default function BatchDetailPage() {
  const { data: session } = useSession() || {};
  const router = useRouter();
  const params = useParams();
  const { toast } = useToast();
  const [batch, setBatch] = useState<BatchDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [availableFiles, setAvailableFiles] = useState<CollectionFile[]>([]);
  const [selectedFiles, setSelectedFiles] = useState<string[]>([]);
  const [selectedBatchFiles, setSelectedBatchFiles] = useState<string[]>([]);
  const [showAddDialog, setShowAddDialog] = useState(false);

  const canManageBatches = session?.user?.role === 'ADMIN' || session?.user?.role === 'MANAGER';

  const fetchBatch = useCallback(async () => {
    try {
      const res = await fetch(`/api/batches/${params.id}`);
      if (res.ok) {
        const data = await res.json();
        setBatch(data);
      } else {
        toast({ title: 'Error', description: 'Failed to fetch batch', variant: 'destructive' });
        router.push('/batches');
      }
    } catch (error) {
      console.error('Error fetching batch:', error);
    } finally {
      setLoading(false);
    }
  }, [params.id, router, toast]);

  const fetchAvailableFiles = async () => {
    try {
      const res = await fetch('/api/collection-files?unassignedBatch=true');
      if (res.ok) {
        const data = await res.json();
        setAvailableFiles(data.files || []);
      }
    } catch (error) {
      console.error('Error fetching available files:', error);
    }
  };

  useEffect(() => {
    fetchBatch();
  }, [fetchBatch]);

  useEffect(() => {
    if (showAddDialog) {
      fetchAvailableFiles();
    }
  }, [showAddDialog]);

  const handleAddFiles = async () => {
    if (selectedFiles.length === 0) return;
    try {
      const res = await fetch(`/api/batches/${params.id}/files`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ fileIds: selectedFiles, action: 'assign' })
      });

      if (res.ok) {
        toast({ title: 'Success', description: `${selectedFiles.length} files added to batch` });
        setShowAddDialog(false);
        setSelectedFiles([]);
        fetchBatch();
      } else {
        const data = await res.json();
        toast({ title: 'Error', description: data.error, variant: 'destructive' });
      }
    } catch (error) {
      toast({ title: 'Error', description: 'Failed to add files', variant: 'destructive' });
    }
  };

  const handleRemoveFiles = async () => {
    if (selectedBatchFiles.length === 0) return;
    if (!confirm(`Remove ${selectedBatchFiles.length} files from this batch?`)) return;
    
    try {
      const res = await fetch(`/api/batches/${params.id}/files`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ fileIds: selectedBatchFiles, action: 'unassign' })
      });

      if (res.ok) {
        toast({ title: 'Success', description: `${selectedBatchFiles.length} files removed from batch` });
        setSelectedBatchFiles([]);
        fetchBatch();
      } else {
        const data = await res.json();
        toast({ title: 'Error', description: data.error, variant: 'destructive' });
      }
    } catch (error) {
      toast({ title: 'Error', description: 'Failed to remove files', variant: 'destructive' });
    }
  };

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('en-KE', { style: 'currency', currency: 'KES' }).format(amount);
  };

  const getStatusBadge = (status: string) => {
    const variants: Record<string, 'default' | 'secondary' | 'destructive' | 'outline'> = {
      NEW: 'secondary',
      IN_PROGRESS: 'default',
      PAID: 'outline',
      DEFAULTED: 'destructive'
    };
    return <Badge variant={variants[status] || 'secondary'}>{status.replace('_', ' ')}</Badge>;
  };

  if (loading) {
    return (
      <ProtectedLayout>
        <div className="text-center py-8">Loading batch details...</div>
      </ProtectedLayout>
    );
  }

  if (!batch) {
    return (
      <ProtectedLayout>
        <div className="text-center py-8">Batch not found</div>
      </ProtectedLayout>
    );
  }

  const collectionRate = batch.totalToCollect > 0 
    ? ((batch.totalCollected / batch.totalToCollect) * 100).toFixed(1) 
    : '0';

  return (
    <ProtectedLayout>
      <div className="space-y-6">
        {/* Header */}
        <div className="flex items-center gap-4">
          <Button variant="ghost" onClick={() => router.push('/batches')}>
            <ArrowLeft className="h-4 w-4 mr-2" />
            Back
          </Button>
          <div className="flex-1">
            <div className="flex items-center gap-2">
              <h1 className="text-2xl font-bold">{batch.name}</h1>
              <Badge variant={batch.isActive ? 'default' : 'secondary'}>
                {batch.isActive ? 'Active' : 'Inactive'}
              </Badge>
            </div>
            {batch.clientName && (
              <p className="text-muted-foreground">Client: {batch.clientName}</p>
            )}
          </div>
        </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className="p-2 bg-blue-100 rounded-lg">
                  <FileText className="h-6 w-6 text-blue-600" />
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">Total Files</p>
                  <p className="text-2xl font-bold">{batch.collectionFiles.length}</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className="p-2 bg-orange-100 rounded-lg">
                  <DollarSign className="h-6 w-6 text-orange-600" />
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">To Collect</p>
                  <p className="text-xl font-bold">{formatCurrency(batch.totalToCollect)}</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className="p-2 bg-green-100 rounded-lg">
                  <TrendingUp className="h-6 w-6 text-green-600" />
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">Collected</p>
                  <p className="text-xl font-bold text-green-600">{formatCurrency(batch.totalCollected)}</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className="p-2 bg-purple-100 rounded-lg">
                  <Users className="h-6 w-6 text-purple-600" />
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">Collection Rate</p>
                  <p className="text-2xl font-bold">{collectionRate}%</p>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Batch Info */}
        {(batch.description || batch.startDate || batch.endDate) && (
          <Card>
            <CardContent className="pt-6">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                {batch.description && (
                  <div className="md:col-span-2">
                    <p className="text-sm text-muted-foreground mb-1">Description</p>
                    <p>{batch.description}</p>
                  </div>
                )}
                {(batch.startDate || batch.endDate) && (
                  <div>
                    <p className="text-sm text-muted-foreground mb-1">Duration</p>
                    <div className="flex items-center gap-2">
                      <Calendar className="h-4 w-4 text-muted-foreground" />
                      {batch.startDate && format(new Date(batch.startDate), 'MMM d, yyyy')}
                      {batch.startDate && batch.endDate && ' - '}
                      {batch.endDate && format(new Date(batch.endDate), 'MMM d, yyyy')}
                    </div>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>
        )}

        {/* Files Table */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <CardTitle>Collection Files ({batch.collectionFiles.length})</CardTitle>
            <div className="flex gap-2">
              {canManageBatches && selectedBatchFiles.length > 0 && (
                <Button variant="outline" onClick={handleRemoveFiles}>
                  <Minus className="h-4 w-4 mr-2" />
                  Remove Selected ({selectedBatchFiles.length})
                </Button>
              )}
              {canManageBatches && (
                <Dialog open={showAddDialog} onOpenChange={setShowAddDialog}>
                  <DialogTrigger asChild>
                    <Button>
                      <Plus className="h-4 w-4 mr-2" />
                      Add Files
                    </Button>
                  </DialogTrigger>
                  <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
                    <DialogHeader>
                      <DialogTitle>Add Files to Batch</DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4">
                      <p className="text-sm text-muted-foreground">
                        Select files without a batch assignment to add to this batch.
                      </p>
                      {availableFiles.length === 0 ? (
                        <p className="text-center py-4 text-muted-foreground">
                          No unassigned files available
                        </p>
                      ) : (
                        <>
                          <Table>
                            <TableHeader>
                              <TableRow>
                                <TableHead className="w-12">
                                  <Checkbox
                                    checked={selectedFiles.length === availableFiles.length && availableFiles.length > 0}
                                    onCheckedChange={(checked) => {
                                      setSelectedFiles(checked ? availableFiles.map(f => f.id) : []);
                                    }}
                                  />
                                </TableHead>
                                <TableHead>Customer</TableHead>
                                <TableHead>Phone</TableHead>
                                <TableHead>To Collect</TableHead>
                                <TableHead>Status</TableHead>
                              </TableRow>
                            </TableHeader>
                            <TableBody>
                              {availableFiles.map((file) => (
                                <TableRow key={file.id}>
                                  <TableCell>
                                    <Checkbox
                                      checked={selectedFiles.includes(file.id)}
                                      onCheckedChange={(checked) => {
                                        setSelectedFiles(prev =>
                                          checked
                                            ? [...prev, file.id]
                                            : prev.filter(id => id !== file.id)
                                        );
                                      }}
                                    />
                                  </TableCell>
                                  <TableCell className="font-medium">{file.customerName}</TableCell>
                                  <TableCell>{file.phoneNumber}</TableCell>
                                  <TableCell>{formatCurrency(file.totalToCollect)}</TableCell>
                                  <TableCell>{getStatusBadge(file.status)}</TableCell>
                                </TableRow>
                              ))}
                            </TableBody>
                          </Table>
                          <div className="flex justify-end gap-2">
                            <Button variant="outline" onClick={() => setShowAddDialog(false)}>
                              Cancel
                            </Button>
                            <Button onClick={handleAddFiles} disabled={selectedFiles.length === 0}>
                              Add {selectedFiles.length} Files
                            </Button>
                          </div>
                        </>
                      )}
                    </div>
                  </DialogContent>
                </Dialog>
              )}
            </div>
          </CardHeader>
          <CardContent>
            {batch.collectionFiles.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                <FileText className="h-12 w-12 mx-auto mb-4 opacity-50" />
                <p>No files in this batch yet</p>
                {canManageBatches && (
                  <Button className="mt-4" onClick={() => setShowAddDialog(true)}>
                    <Plus className="h-4 w-4 mr-2" />
                    Add Files
                  </Button>
                )}
              </div>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    {canManageBatches && (
                      <TableHead className="w-12">
                        <Checkbox
                          checked={selectedBatchFiles.length === batch.collectionFiles.length && batch.collectionFiles.length > 0}
                          onCheckedChange={(checked) => {
                            setSelectedBatchFiles(checked ? batch.collectionFiles.map(f => f.id) : []);
                          }}
                        />
                      </TableHead>
                    )}
                    <TableHead>Customer</TableHead>
                    <TableHead>Phone</TableHead>
                    <TableHead>Agent</TableHead>
                    <TableHead>To Collect</TableHead>
                    <TableHead>Outstanding</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead className="w-20">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {batch.collectionFiles.map((file) => (
                    <TableRow key={file.id}>
                      {canManageBatches && (
                        <TableCell>
                          <Checkbox
                            checked={selectedBatchFiles.includes(file.id)}
                            onCheckedChange={(checked) => {
                              setSelectedBatchFiles(prev =>
                                checked
                                  ? [...prev, file.id]
                                  : prev.filter(id => id !== file.id)
                              );
                            }}
                          />
                        </TableCell>
                      )}
                      <TableCell className="font-medium">{file.customerName}</TableCell>
                      <TableCell>{file.phoneNumber}</TableCell>
                      <TableCell>{file.assignedAgent?.name || '-'}</TableCell>
                      <TableCell>{formatCurrency(file.totalToCollect)}</TableCell>
                      <TableCell>{formatCurrency(file.outstandingBalance)}</TableCell>
                      <TableCell>{getStatusBadge(file.status)}</TableCell>
                      <TableCell>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => router.push(`/files/${file.id}`)}
                        >
                          <Eye className="h-4 w-4" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            )}
          </CardContent>
        </Card>
      </div>
    </ProtectedLayout>
  );
}
