"use client";

import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { useRouter, useParams } from "next/navigation";
import Link from "next/link";
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 { Badge } from "@/components/ui/badge";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useToast } from "@/hooks/use-toast";
import { ArrowLeft, Plus, Trash2, Edit, Phone, FileText, Calendar, CheckCircle, XCircle, Clock, PhoneCall, PhoneOff, PhoneMissed, MessageSquare, Send, Brain, TrendingUp, Target, Lightbulb, RefreshCw, AlertTriangle, ThumbsUp, ThumbsDown, ArrowUpRight, ArrowDownLeft, Mail, Banknote, History, Smartphone, Loader2, ChevronLeft, ChevronRight } from "lucide-react";
import { ProtectedLayout } from "@/components/protected-layout";

interface Payment {
  id: string;
  amount: number;
  paymentDate: string;
  paymentMethod: string;
  referenceNumber: string | null;
  notes: string | null;
}

interface Activity {
  id: string;
  type: string;
  description: string;
  contactNumber: string | null;
  outcome: string | null;
  activityDate: string;
  user: { id: string; name: string };
}

interface PromiseToPay {
  id: string;
  promisedAmount: number;
  promisedDate: string;
  status: string;
  notes: string | null;
  followUpDate: string | null;
  user: { id: string; name: string };
}

interface CollectionFile {
  id: string;
  customerName: string;
  phoneNumber: string;
  idNumber: string | null;
  alias: string | null;
  appliedAmount: number;
  allocatedAmount: number;
  commission: number;
  vat: number;
  totalToCollect: number;
  outstandingBalance: number;
  status: string;
  dateOutsourced: string | null;
  assignedAgent: { id: string; name: string; email: string } | null;
  payments: Payment[];
}

interface AIPrediction {
  id: string;
  paymentProbability: number;
  riskLevel: string;
  optimalChannel: string | null;
  optimalTimeSlot: string | null;
  optimalDayOfWeek: string | null;
  nextBestAction: string;
  keyInsights: string[];
  patterns: string[];
  confidence: number;
  createdAt: string;
}

interface TimelineItem {
  id: string;
  type: string;
  channel: string;
  direction: string;
  content: string;
  status: string;
  outcome?: string;
  duration?: number;
  amount?: number;
  createdBy?: string;
  createdAt: string;
  isAutomated?: boolean;
}

export default function FileDetailPage() {
  const params = useParams();
  const router = useRouter();
  const { toast } = useToast();
  const { data: session } = useSession() || {};
  const [file, setFile] = useState<CollectionFile | null>(null);
  const [activities, setActivities] = useState<Activity[]>([]);
  const [promises, setPromises] = useState<PromiseToPay[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isPaymentDialogOpen, setIsPaymentDialogOpen] = useState(false);
  const [isActivityDialogOpen, setIsActivityDialogOpen] = useState(false);
  const [isPromiseDialogOpen, setIsPromiseDialogOpen] = useState(false);
  const [isCallDialogOpen, setIsCallDialogOpen] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [agents, setAgents] = useState<any[]>([]);

  // Navigation between files
  const [allFiles, setAllFiles] = useState<{ id: string; customerName: string }[]>([]);
  const [currentFileIndex, setCurrentFileIndex] = useState<number>(-1);

  const [callFormData, setCallFormData] = useState({
    outcome: "",
    description: "",
    followUpRequired: false,
  });

  const [isSmsDialogOpen, setIsSmsDialogOpen] = useState(false);
  const [smsFormData, setSmsFormData] = useState({
    message: "",
  });
  const [isSendingSms, setIsSendingSms] = useState(false);

  // AI Prediction states
  const [aiPrediction, setAiPrediction] = useState<AIPrediction | null>(null);
  const [isLoadingAi, setIsLoadingAi] = useState(false);
  const [isFeedbackDialogOpen, setIsFeedbackDialogOpen] = useState(false);
  const [feedbackData, setFeedbackData] = useState({
    actionTaken: "",
    actionOutcome: "",
    notes: ""
  });

  // Timeline state
  const [timeline, setTimeline] = useState<TimelineItem[]>([]);
  const [timelineStats, setTimelineStats] = useState({
    totalCalls: 0,
    totalSms: 0,
    totalEmails: 0,
    totalPayments: 0,
    totalPromises: 0,
    lastContact: null as string | null,
    inboundMessages: 0,
  });

  // M-Pesa STK Push state
  const [isMpesaDialogOpen, setIsMpesaDialogOpen] = useState(false);
  const [mpesaFormData, setMpesaFormData] = useState({
    phoneNumber: "",
    amount: "",
  });
  const [isInitiatingMpesa, setIsInitiatingMpesa] = useState(false);
  const [pendingMpesaTxId, setPendingMpesaTxId] = useState<string | null>(null);

  const [paymentFormData, setPaymentFormData] = useState({
    amount: "",
    paymentDate: new Date().toISOString().split("T")[0],
    paymentMethod: "CASH",
    referenceNumber: "",
    notes: "",
  });

  const [activityFormData, setActivityFormData] = useState({
    type: "CALL",
    description: "",
    contactNumber: "",
    outcome: "",
    activityDate: new Date().toISOString().split("T")[0],
  });

  const [promiseFormData, setPromiseFormData] = useState({
    promisedAmount: "",
    promisedDate: "",
    notes: "",
    followUpDate: "",
  });

  const [editFormData, setEditFormData] = useState({
    customerName: "",
    phoneNumber: "",
    idNumber: "",
    alias: "",
    appliedAmount: "",
    allocatedAmount: "",
    assignedAgentId: "",
    dateOutsourced: "",
    status: "NEW",
  });

  useEffect(() => {
    if (params?.id) {
      fetchFile();
      fetchAgents();
      fetchActivities();
      fetchPromises();
      fetchAiPrediction();
      fetchTimeline();
      fetchAllFiles();
    }
  }, [params?.id]);

  // Fetch all files for navigation
  const fetchAllFiles = async () => {
    try {
      const res = await fetch("/api/collection-files");
      if (res.ok) {
        const data = await res.json();
        const files = data?.files ?? [];
        setAllFiles(files.map((f: any) => ({ id: f.id, customerName: f.customerName })));
        const index = files.findIndex((f: any) => f.id === params?.id);
        setCurrentFileIndex(index);
      }
    } catch (error) {
      console.error("Error fetching all files:", error);
    }
  };

  const goToPreviousFile = () => {
    if (currentFileIndex > 0) {
      router.push(`/files/${allFiles[currentFileIndex - 1].id}`);
    }
  };

  const goToNextFile = () => {
    if (currentFileIndex < allFiles.length - 1) {
      router.push(`/files/${allFiles[currentFileIndex + 1].id}`);
    }
  };

  const fetchTimeline = async () => {
    try {
      const res = await fetch(`/api/communications/timeline?collectionFileId=${params?.id}`);
      if (res.ok) {
        const data = await res.json();
        setTimeline(data.timeline || []);
        setTimelineStats(data.stats || {});
      }
    } catch (error) {
      console.error("Error fetching timeline:", error);
    }
  };

  const fetchAiPrediction = async (refresh = false) => {
    try {
      setIsLoadingAi(true);
      const res = await fetch(`/api/ai/predictions?fileId=${params?.id}${refresh ? '&refresh=true' : ''}`);
      if (res.ok) {
        const data = await res.json();
        setAiPrediction(data.prediction);
      }
    } catch (error) {
      console.error("Error fetching AI prediction:", error);
    } finally {
      setIsLoadingAi(false);
    }
  };

  const handleSubmitFeedback = async () => {
    if (!feedbackData.actionTaken || !feedbackData.actionOutcome) {
      toast({ title: "Error", description: "Please select action and outcome", variant: "destructive" });
      return;
    }
    try {
      const res = await fetch("/api/ai/feedback", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          collectionFileId: params?.id,
          actionTaken: feedbackData.actionTaken,
          actionOutcome: feedbackData.actionOutcome,
          predictedProbability: aiPrediction?.paymentProbability,
          notes: feedbackData.notes
        })
      });
      if (res.ok) {
        toast({ title: "Success", description: "Feedback recorded - AI will learn from this" });
        setIsFeedbackDialogOpen(false);
        setFeedbackData({ actionTaken: "", actionOutcome: "", notes: "" });
      }
    } catch (error) {
      toast({ title: "Error", description: "Failed to submit feedback", variant: "destructive" });
    }
  };

  const fetchFile = async () => {
    try {
      setIsLoading(true);
      const res = await fetch(`/api/collection-files/${params?.id}`);
      if (res.ok) {
        const data = await res.json();
        setFile(data?.file);
        setEditFormData({
          customerName: data?.file?.customerName ?? "",
          phoneNumber: data?.file?.phoneNumber ?? "",
          idNumber: data?.file?.idNumber ?? "",
          alias: data?.file?.alias ?? "",
          appliedAmount: data?.file?.appliedAmount?.toString() ?? "",
          allocatedAmount: data?.file?.allocatedAmount?.toString() ?? "",
          assignedAgentId: data?.file?.assignedAgent?.id ?? "",
          dateOutsourced: data?.file?.dateOutsourced
            ? new Date(data?.file?.dateOutsourced).toISOString().split("T")[0]
            : "",
          status: data?.file?.status ?? "NEW",
        });
      }
    } catch (error) {
      console.error("Error fetching file:", error);
      toast({ title: "Error", description: "Failed to fetch file details", variant: "destructive" });
    } finally {
      setIsLoading(false);
    }
  };

  const fetchAgents = async () => {
    try {
      const res = await fetch("/api/users?role=AGENT");
      if (res.ok) {
        const data = await res.json();
        setAgents(data?.users ?? []);
      }
    } catch (error) {
      console.error("Error fetching agents:", error);
    }
  };

  const fetchActivities = async () => {
    try {
      const res = await fetch(`/api/activities?collectionFileId=${params?.id}`);
      if (res.ok) {
        const data = await res.json();
        setActivities(data?.activities ?? []);
      }
    } catch (error) {
      console.error("Error fetching activities:", error);
    }
  };

  const fetchPromises = async () => {
    try {
      const res = await fetch(`/api/promises?collectionFileId=${params?.id}`);
      if (res.ok) {
        const data = await res.json();
        setPromises(data?.promises ?? []);
      }
    } catch (error) {
      console.error("Error fetching promises:", error);
    }
  };

  const handleAddPayment = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const res = await fetch("/api/payments", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ collectionFileId: params?.id, ...paymentFormData }),
      });
      if (!res.ok) throw new Error("Failed to add payment");
      toast({ title: "Success", description: "Payment recorded successfully" });
      setIsPaymentDialogOpen(false);
      setPaymentFormData({ amount: "", paymentDate: new Date().toISOString().split("T")[0], paymentMethod: "CASH", referenceNumber: "", notes: "" });
      fetchFile();
    } catch (error) {
      toast({ title: "Error", description: "Failed to record payment", variant: "destructive" });
    }
  };

  const handleAddActivity = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const res = await fetch("/api/activities", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ collectionFileId: params?.id, ...activityFormData }),
      });
      if (!res.ok) throw new Error("Failed to add activity");
      toast({ title: "Success", description: "Activity logged successfully" });
      setIsActivityDialogOpen(false);
      setActivityFormData({ type: "CALL", description: "", contactNumber: "", outcome: "", activityDate: new Date().toISOString().split("T")[0] });
      fetchActivities();
    } catch (error) {
      toast({ title: "Error", description: "Failed to log activity", variant: "destructive" });
    }
  };

  const handleAddPromise = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const res = await fetch("/api/promises", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ collectionFileId: params?.id, ...promiseFormData }),
      });
      if (!res.ok) throw new Error("Failed to add promise");
      toast({ title: "Success", description: "Promise to pay recorded" });
      setIsPromiseDialogOpen(false);
      setPromiseFormData({ promisedAmount: "", promisedDate: "", notes: "", followUpDate: "" });
      fetchPromises();
    } catch (error) {
      toast({ title: "Error", description: "Failed to record promise", variant: "destructive" });
    }
  };

  const handleUpdatePromiseStatus = async (promiseId: string, status: string) => {
    try {
      const res = await fetch(`/api/promises/${promiseId}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status }),
      });
      if (!res.ok) throw new Error("Failed to update promise");
      toast({ title: "Success", description: "Promise status updated" });
      fetchPromises();
    } catch (error) {
      toast({ title: "Error", description: "Failed to update promise", variant: "destructive" });
    }
  };

  const handleUpdateFile = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const res = await fetch(`/api/collection-files/${params?.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...editFormData,
          appliedAmount: parseFloat(editFormData.appliedAmount) || 0,
          allocatedAmount: parseFloat(editFormData.allocatedAmount) || 0,
        }),
      });
      if (!res.ok) throw new Error("Failed to update file");
      toast({ title: "Success", description: "File updated successfully" });
      setIsEditing(false);
      fetchFile();
    } catch (error) {
      toast({ title: "Error", description: "Failed to update file", variant: "destructive" });
    }
  };

  const handleDelete = async () => {
    if (!confirm("Are you sure you want to delete this file?")) return;
    try {
      const res = await fetch(`/api/collection-files/${params?.id}`, { method: "DELETE" });
      if (!res.ok) throw new Error("Failed to delete file");
      toast({ title: "Success", description: "File deleted successfully" });
      router.push("/files");
    } catch (error) {
      toast({ title: "Error", description: "Failed to delete file", variant: "destructive" });
    }
  };

  const handleDeletePayment = async (paymentId: string) => {
    if (!confirm("Are you sure you want to delete this payment?")) return;
    try {
      const res = await fetch(`/api/payments/${paymentId}`, { method: "DELETE" });
      if (!res.ok) throw new Error("Failed to delete payment");
      toast({ title: "Success", description: "Payment deleted successfully" });
      fetchFile();
    } catch (error) {
      toast({ title: "Error", description: "Failed to delete payment", variant: "destructive" });
    }
  };

  // M-Pesa STK Push functions
  const handleOpenMpesaDialog = () => {
    if (file) {
      setMpesaFormData({
        phoneNumber: file.phoneNumber,
        amount: file.outstandingBalance.toString(),
      });
    }
    setIsMpesaDialogOpen(true);
  };

  const handleInitiateMpesa = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!mpesaFormData.phoneNumber || !mpesaFormData.amount) {
      toast({ title: "Error", description: "Phone number and amount are required", variant: "destructive" });
      return;
    }

    setIsInitiatingMpesa(true);
    try {
      const res = await fetch("/api/mpesa/stkpush", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          collectionFileId: params?.id,
          phoneNumber: mpesaFormData.phoneNumber,
          amount: parseFloat(mpesaFormData.amount),
          description: `Payment for ${file?.customerName}`,
        }),
      });

      const data = await res.json();

      if (res.ok && data.success) {
        toast({ title: "M-Pesa Request Sent", description: data.message || "Check customer's phone" });
        setIsMpesaDialogOpen(false);
        setPendingMpesaTxId(data.transaction.id);
        setMpesaFormData({ phoneNumber: "", amount: "" });
      } else {
        toast({ title: "Error", description: data.error || "Failed to initiate payment", variant: "destructive" });
      }
    } catch (error) {
      toast({ title: "Error", description: "Failed to initiate M-Pesa payment", variant: "destructive" });
    } finally {
      setIsInitiatingMpesa(false);
    }
  };

  // Poll for M-Pesa transaction status
  useEffect(() => {
    if (!pendingMpesaTxId) return;

    const interval = setInterval(async () => {
      try {
        const res = await fetch(`/api/mpesa/status?transactionId=${pendingMpesaTxId}`);
        if (res.ok) {
          const data = await res.json();
          if (data.transaction.status !== "PENDING") {
            setPendingMpesaTxId(null);
            fetchFile();

            if (data.transaction.status === "COMPLETED") {
              toast({ title: "Payment Successful!", description: `KES ${data.transaction.amount.toLocaleString()} received` });
            } else {
              toast({ title: "Payment Status", description: data.transaction.resultDesc || "Transaction completed", variant: data.transaction.status === "CANCELLED" ? "default" : "destructive" });
            }
          }
        }
      } catch (error) {
        console.error("Polling error:", error);
      }
    }, 5000);

    return () => clearInterval(interval);
  }, [pendingMpesaTxId]);

  const handleMakeCall = () => {
    if (!file?.phoneNumber) {
      toast({ title: "Error", description: "No phone number available", variant: "destructive" });
      return;
    }
    // Format phone number for tel: link (Kenya format)
    let phoneNumber = file.phoneNumber.replace(/\s+/g, "").replace(/-/g, "");
    if (phoneNumber.startsWith("0")) {
      phoneNumber = "+254" + phoneNumber.substring(1);
    } else if (!phoneNumber.startsWith("+")) {
      phoneNumber = "+254" + phoneNumber;
    }
    // Open phone dialer
    window.open(`tel:${phoneNumber}`, "_self");
    // Open the call logging dialog after a brief delay
    setTimeout(() => {
      setIsCallDialogOpen(true);
    }, 500);
  };

  const handleLogCall = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const res = await fetch("/api/activities", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          collectionFileId: params?.id,
          type: "CALL",
          description: callFormData.description || `Call to customer - ${callFormData.outcome}`,
          contactNumber: file?.phoneNumber,
          outcome: callFormData.outcome,
          activityDate: new Date().toISOString().split("T")[0],
        }),
      });
      if (!res.ok) throw new Error("Failed to log call");
      toast({ title: "Success", description: "Call logged successfully" });
      setIsCallDialogOpen(false);
      setCallFormData({ outcome: "", description: "", followUpRequired: false });
      fetchActivities();
    } catch (error) {
      toast({ title: "Error", description: "Failed to log call", variant: "destructive" });
    }
  };

  const handleSendSms = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!file?.phoneNumber || !smsFormData.message.trim()) {
      toast({ title: "Error", description: "Phone number and message are required", variant: "destructive" });
      return;
    }
    
    setIsSendingSms(true);
    try {
      const res = await fetch("/api/sms", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          phoneNumber: file.phoneNumber,
          message: smsFormData.message,
          collectionFileId: params?.id,
        }),
      });
      
      if (!res.ok) {
        const error = await res.json();
        throw new Error(error.error || "Failed to send SMS");
      }
      
      toast({ title: "Success", description: "SMS sent successfully" });
      setIsSmsDialogOpen(false);
      setSmsFormData({ message: "" });
      fetchActivities();
    } catch (error: any) {
      toast({ title: "Error", description: error.message || "Failed to send SMS", variant: "destructive" });
    } finally {
      setIsSendingSms(false);
    }
  };

  const smsTemplates = [
    { name: "Payment Reminder", message: `Dear ${file?.customerName || "Customer"}, this is a reminder about your outstanding balance of KES ${file?.outstandingBalance?.toLocaleString() || "0"}. Please make payment at your earliest convenience. - Greco` },
    { name: "Promise Follow-up", message: `Dear ${file?.customerName || "Customer"}, we are following up on your payment commitment. Kindly update us on the status. - Greco` },
    { name: "Thank You", message: `Dear ${file?.customerName || "Customer"}, thank you for your recent payment. Your cooperation is appreciated. - Greco` },
  ];

  const formatCurrency = (amount: number) => new Intl.NumberFormat("en-KE", { style: "currency", currency: "KES" }).format(amount ?? 0);
  const formatDate = (date: string) => new Date(date).toLocaleDateString("en-KE", { year: "numeric", month: "short", day: "numeric" });

  const getStatusColor = (status: string) => {
    switch (status) {
      case "NEW": return "bg-blue-100 text-blue-800";
      case "IN_PROGRESS": return "bg-yellow-100 text-yellow-800";
      case "PAID": return "bg-green-100 text-green-800";
      case "DEFAULTED": return "bg-red-100 text-red-800";
      default: return "bg-gray-100 text-gray-800";
    }
  };

  const getPromiseStatusColor = (status: string) => {
    switch (status) {
      case "PENDING": return "bg-yellow-100 text-yellow-800";
      case "KEPT": return "bg-green-100 text-green-800";
      case "BROKEN": return "bg-red-100 text-red-800";
      case "RESCHEDULED": return "bg-blue-100 text-blue-800";
      default: return "bg-gray-100 text-gray-800";
    }
  };

  const getActivityIcon = (type: string) => {
    switch (type) {
      case "CALL": return <Phone className="h-4 w-4" />;
      case "NOTE": return <FileText className="h-4 w-4" />;
      case "VISIT": return <Calendar className="h-4 w-4" />;
      default: return <FileText className="h-4 w-4" />;
    }
  };

  if (isLoading) {
    return (
      <ProtectedLayout>
        <div className="flex h-screen items-center justify-center"><div className="text-lg">Loading...</div></div>
      </ProtectedLayout>
    );
  }

  if (!file) {
    return (
      <ProtectedLayout>
        <div className="p-8"><p>File not found</p></div>
      </ProtectedLayout>
    );
  }

  const isAdmin = session?.user?.role === "ADMIN";
  const isManager = session?.user?.role === "MANAGER";
  const canEdit = isAdmin || isManager;

  return (
    <ProtectedLayout>
      <div className="p-8">
        {/* Navigation Header */}
        <div className="flex items-center justify-between mb-4">
          <Link href="/files">
            <Button variant="ghost"><ArrowLeft className="mr-2 h-4 w-4" />Back to Files</Button>
          </Link>
          
          {/* File Navigation */}
          {allFiles.length > 0 && currentFileIndex >= 0 && (
            <div className="flex items-center gap-2 bg-gradient-to-r from-blue-600 to-blue-700 rounded-lg px-4 py-2 text-white shadow-lg">
              <Button
                variant="ghost"
                size="sm"
                onClick={goToPreviousFile}
                disabled={currentFileIndex <= 0}
                className="text-white hover:bg-blue-500 disabled:opacity-50 h-8 px-2"
              >
                <ChevronLeft className="h-5 w-5" />
                <span className="hidden sm:inline ml-1">Previous</span>
              </Button>
              
              <div className="text-center px-3 border-l border-r border-blue-400">
                <p className="text-xs opacity-80">Customer</p>
                <p className="font-semibold text-sm">
                  #{currentFileIndex + 1} of {allFiles.length}
                </p>
              </div>
              
              <Button
                variant="ghost"
                size="sm"
                onClick={goToNextFile}
                disabled={currentFileIndex >= allFiles.length - 1}
                className="text-white hover:bg-blue-500 disabled:opacity-50 h-8 px-2"
              >
                <span className="hidden sm:inline mr-1">Next</span>
                <ChevronRight className="h-5 w-5" />
              </Button>
            </div>
          )}
        </div>

        <div className="flex items-start justify-between mb-6">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">{file?.customerName}</h1>
            <Badge className={`${getStatusColor(file?.status ?? "")} mt-2`}>{file?.status?.replace("_", " ")}</Badge>
          </div>
          <div className="flex gap-2">
            {!isEditing && (
              <>
                <Button onClick={handleMakeCall} className="bg-green-600 hover:bg-green-700 text-white">
                  <PhoneCall className="mr-2 h-4 w-4" />Make Call
                </Button>
                <Button onClick={() => setIsSmsDialogOpen(true)} className="bg-blue-600 hover:bg-blue-700 text-white">
                  <MessageSquare className="mr-2 h-4 w-4" />Send SMS
                </Button>
                <Button variant="outline" onClick={() => setIsEditing(true)}><Edit className="mr-2 h-4 w-4" />Edit</Button>
                {canEdit && (
                  <Button variant="destructive" onClick={handleDelete}><Trash2 className="mr-2 h-4 w-4" />Delete</Button>
                )}
              </>
            )}
          </div>

          {/* Call Logging Dialog */}
          <Dialog open={isCallDialogOpen} onOpenChange={setIsCallDialogOpen}>
            <DialogContent>
              <DialogHeader>
                <DialogTitle className="flex items-center gap-2">
                  <Phone className="h-5 w-5" />
                  Log Call Outcome
                </DialogTitle>
                <DialogDescription>
                  Record the outcome of your call with {file?.customerName} ({file?.phoneNumber})
                </DialogDescription>
              </DialogHeader>
              <form onSubmit={handleLogCall} className="space-y-4">
                <div>
                  <Label>Call Outcome</Label>
                  <Select 
                    value={callFormData.outcome} 
                    onValueChange={(value) => setCallFormData({ ...callFormData, outcome: value })}
                  >
                    <SelectTrigger><SelectValue placeholder="Select outcome" /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="CONNECTED">
                        <div className="flex items-center gap-2">
                          <CheckCircle className="h-4 w-4 text-green-500" />Connected - Spoke with customer
                        </div>
                      </SelectItem>
                      <SelectItem value="NO_ANSWER">
                        <div className="flex items-center gap-2">
                          <PhoneMissed className="h-4 w-4 text-yellow-500" />No Answer
                        </div>
                      </SelectItem>
                      <SelectItem value="BUSY">
                        <div className="flex items-center gap-2">
                          <PhoneOff className="h-4 w-4 text-orange-500" />Line Busy
                        </div>
                      </SelectItem>
                      <SelectItem value="VOICEMAIL">
                        <div className="flex items-center gap-2">
                          <Phone className="h-4 w-4 text-blue-500" />Left Voicemail
                        </div>
                      </SelectItem>
                      <SelectItem value="WRONG_NUMBER">
                        <div className="flex items-center gap-2">
                          <XCircle className="h-4 w-4 text-red-500" />Wrong Number
                        </div>
                      </SelectItem>
                      <SelectItem value="CALLBACK_REQUESTED">
                        <div className="flex items-center gap-2">
                          <Clock className="h-4 w-4 text-purple-500" />Callback Requested
                        </div>
                      </SelectItem>
                      <SelectItem value="PROMISE_TO_PAY">
                        <div className="flex items-center gap-2">
                          <CheckCircle className="h-4 w-4 text-green-600" />Promise to Pay
                        </div>
                      </SelectItem>
                      <SelectItem value="REFUSED_TO_PAY">
                        <div className="flex items-center gap-2">
                          <XCircle className="h-4 w-4 text-red-600" />Refused to Pay
                        </div>
                      </SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label>Notes</Label>
                  <Textarea 
                    placeholder="Add any notes about the call..."
                    value={callFormData.description} 
                    onChange={(e) => setCallFormData({ ...callFormData, description: e.target.value })} 
                    rows={3}
                  />
                </div>
                <div className="flex gap-2">
                  <Button type="submit" className="flex-1" disabled={!callFormData.outcome}>
                    Log Call
                  </Button>
                  <Button type="button" variant="outline" onClick={() => setIsCallDialogOpen(false)}>
                    Skip
                  </Button>
                </div>
              </form>
            </DialogContent>
          </Dialog>

          {/* SMS Dialog */}
          <Dialog open={isSmsDialogOpen} onOpenChange={setIsSmsDialogOpen}>
            <DialogContent className="max-w-md">
              <DialogHeader>
                <DialogTitle className="flex items-center gap-2">
                  <MessageSquare className="h-5 w-5" />
                  Send SMS
                </DialogTitle>
                <DialogDescription>
                  Send SMS to {file?.customerName} ({file?.phoneNumber})
                </DialogDescription>
              </DialogHeader>
              <form onSubmit={handleSendSms} className="space-y-4">
                <div>
                  <Label>Quick Templates</Label>
                  <div className="flex flex-wrap gap-2 mt-2">
                    {smsTemplates.map((template, idx) => (
                      <Button
                        key={idx}
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={() => setSmsFormData({ message: template.message })}
                      >
                        {template.name}
                      </Button>
                    ))}
                  </div>
                </div>
                <div>
                  <Label>Message</Label>
                  <Textarea 
                    placeholder="Type your message..."
                    value={smsFormData.message} 
                    onChange={(e) => setSmsFormData({ message: e.target.value })} 
                    rows={4}
                    maxLength={480}
                    required
                  />
                  <p className="text-xs text-gray-500 mt-1">
                    {smsFormData.message.length}/480 characters
                  </p>
                </div>
                <div className="flex gap-2">
                  <Button 
                    type="submit" 
                    className="flex-1 bg-blue-600 hover:bg-blue-700" 
                    disabled={isSendingSms || !smsFormData.message.trim()}
                  >
                    {isSendingSms ? (
                      <>Sending...</>
                    ) : (
                      <><Send className="mr-2 h-4 w-4" />Send SMS</>
                    )}
                  </Button>
                  <Button type="button" variant="outline" onClick={() => setIsSmsDialogOpen(false)}>
                    Cancel
                  </Button>
                </div>
              </form>
            </DialogContent>
          </Dialog>
        </div>

        <div className="grid gap-6 lg:grid-cols-3">
          {/* Left Column - File Details */}
          <div className="lg:col-span-2 space-y-6">
            {isEditing ? (
              <Card>
                <CardHeader><CardTitle>Edit File</CardTitle></CardHeader>
                <CardContent>
                  <form onSubmit={handleUpdateFile} className="space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                      <div><Label>Customer Name</Label><Input value={editFormData.customerName} onChange={(e) => setEditFormData({ ...editFormData, customerName: e.target.value })} required /></div>
                      <div><Label>Phone Number</Label><Input value={editFormData.phoneNumber} onChange={(e) => setEditFormData({ ...editFormData, phoneNumber: e.target.value })} required /></div>
                      <div><Label>ID Number</Label><Input value={editFormData.idNumber} onChange={(e) => setEditFormData({ ...editFormData, idNumber: e.target.value })} /></div>
                      <div><Label>Alias</Label><Input value={editFormData.alias} onChange={(e) => setEditFormData({ ...editFormData, alias: e.target.value })} /></div>
                      <div><Label>Applied Amount</Label><Input type="number" value={editFormData.appliedAmount} onChange={(e) => setEditFormData({ ...editFormData, appliedAmount: e.target.value })} /></div>
                      <div><Label>Allocated Amount</Label><Input type="number" value={editFormData.allocatedAmount} onChange={(e) => setEditFormData({ ...editFormData, allocatedAmount: e.target.value })} /></div>
                      <div><Label>Status</Label>
                        <Select value={editFormData.status} onValueChange={(value) => setEditFormData({ ...editFormData, status: value })}>
                          <SelectTrigger><SelectValue /></SelectTrigger>
                          <SelectContent>
                            <SelectItem value="NEW">New</SelectItem>
                            <SelectItem value="IN_PROGRESS">In Progress</SelectItem>
                            <SelectItem value="PAID">Paid</SelectItem>
                            <SelectItem value="DEFAULTED">Defaulted</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                      <div><Label>Assigned Agent</Label>
                        <Select value={editFormData.assignedAgentId} onValueChange={(value) => setEditFormData({ ...editFormData, assignedAgentId: value })}>
                          <SelectTrigger><SelectValue placeholder="Select Agent" /></SelectTrigger>
                          <SelectContent>
                            {agents.map((agent) => (<SelectItem key={agent.id} value={agent.id}>{agent.name}</SelectItem>))}
                          </SelectContent>
                        </Select>
                      </div>
                      <div><Label>Date Outsourced</Label><Input type="date" value={editFormData.dateOutsourced} onChange={(e) => setEditFormData({ ...editFormData, dateOutsourced: e.target.value })} /></div>
                    </div>
                    <div className="flex gap-2">
                      <Button type="submit">Save Changes</Button>
                      <Button type="button" variant="outline" onClick={() => setIsEditing(false)}>Cancel</Button>
                    </div>
                  </form>
                </CardContent>
              </Card>
            ) : (
              <Card>
                <CardHeader><CardTitle>File Details</CardTitle></CardHeader>
                <CardContent>
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div><span className="text-gray-500">Phone:</span> <span className="font-medium">{file?.phoneNumber}</span></div>
                    <div><span className="text-gray-500">ID Number:</span> <span className="font-medium">{file?.idNumber || "N/A"}</span></div>
                    <div><span className="text-gray-500">Alias:</span> <span className="font-medium">{file?.alias || "N/A"}</span></div>
                    <div><span className="text-gray-500">Assigned Agent:</span> <span className="font-medium">{file?.assignedAgent?.name || "Unassigned"}</span></div>
                    <div><span className="text-gray-500">Date Outsourced:</span> <span className="font-medium">{file?.dateOutsourced ? formatDate(file.dateOutsourced) : "N/A"}</span></div>
                  </div>
                </CardContent>
              </Card>
            )}

            {/* Tabs for Payments, Activities, Promises, Timeline */}
            <Tabs defaultValue="timeline" className="w-full">
              <TabsList className="grid w-full grid-cols-4">
                <TabsTrigger value="timeline">
                  <History className="h-4 w-4 mr-1" />
                  Timeline ({timeline.length})
                </TabsTrigger>
                <TabsTrigger value="payments">Payments ({file?.payments?.length || 0})</TabsTrigger>
                <TabsTrigger value="activities">Activities ({activities.length})</TabsTrigger>
                <TabsTrigger value="promises">Promises ({promises.length})</TabsTrigger>
              </TabsList>

              <TabsContent value="payments">
                <Card>
                  <CardHeader className="flex flex-row items-center justify-between">
                    <CardTitle>Payment History</CardTitle>
                    <div className="flex gap-2">
                      <Button size="sm" variant="outline" className="bg-green-50 border-green-200 hover:bg-green-100 text-green-700" onClick={handleOpenMpesaDialog}>
                        <Smartphone className="mr-2 h-4 w-4" />M-Pesa
                      </Button>
                      <Dialog open={isPaymentDialogOpen} onOpenChange={setIsPaymentDialogOpen}>
                        <DialogTrigger asChild><Button size="sm"><Plus className="mr-2 h-4 w-4" />Add Payment</Button></DialogTrigger>
                        <DialogContent>
                          <DialogHeader><DialogTitle>Record Payment</DialogTitle><DialogDescription>Add a new payment for this collection file.</DialogDescription></DialogHeader>
                          <form onSubmit={handleAddPayment} className="space-y-4">
                            <div><Label>Amount (KES)</Label><Input type="number" step="0.01" value={paymentFormData.amount} onChange={(e) => setPaymentFormData({ ...paymentFormData, amount: e.target.value })} required /></div>
                            <div><Label>Payment Date</Label><Input type="date" value={paymentFormData.paymentDate} onChange={(e) => setPaymentFormData({ ...paymentFormData, paymentDate: e.target.value })} required /></div>
                            <div><Label>Payment Method</Label>
                              <Select value={paymentFormData.paymentMethod} onValueChange={(value) => setPaymentFormData({ ...paymentFormData, paymentMethod: value })}>
                                <SelectTrigger><SelectValue /></SelectTrigger>
                                <SelectContent>
                                  <SelectItem value="CASH">Cash</SelectItem>
                                  <SelectItem value="BANK_TRANSFER">Bank Transfer</SelectItem>
                                  <SelectItem value="M_PESA">M-Pesa</SelectItem>
                                  <SelectItem value="CHEQUE">Cheque</SelectItem>
                                </SelectContent>
                              </Select>
                            </div>
                            <div><Label>Reference Number</Label><Input value={paymentFormData.referenceNumber} onChange={(e) => setPaymentFormData({ ...paymentFormData, referenceNumber: e.target.value })} /></div>
                            <div><Label>Notes</Label><Textarea value={paymentFormData.notes} onChange={(e) => setPaymentFormData({ ...paymentFormData, notes: e.target.value })} /></div>
                            <Button type="submit" className="w-full">Record Payment</Button>
                          </form>
                        </DialogContent>
                      </Dialog>
                    </div>
                  </CardHeader>
                  <CardContent>
                    {file?.payments?.length === 0 ? (<p className="text-gray-500 text-center py-4">No payments recorded yet.</p>) : (
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>Date</TableHead>
                            <TableHead>Amount</TableHead>
                            <TableHead>Method</TableHead>
                            <TableHead>Reference</TableHead>
                            {canEdit && <TableHead></TableHead>}
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {file?.payments?.map((payment) => (
                            <TableRow key={payment.id}>
                              <TableCell>{formatDate(payment.paymentDate)}</TableCell>
                              <TableCell className="font-medium">{formatCurrency(payment.amount)}</TableCell>
                              <TableCell>{payment.paymentMethod.replace("_", " ")}</TableCell>
                              <TableCell>{payment.referenceNumber || "N/A"}</TableCell>
                              {canEdit && (<TableCell><Button variant="ghost" size="sm" onClick={() => handleDeletePayment(payment.id)}><Trash2 className="h-4 w-4 text-red-500" /></Button></TableCell>)}
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    )}
                  </CardContent>
                </Card>
              </TabsContent>

              <TabsContent value="activities">
                <Card>
                  <CardHeader className="flex flex-row items-center justify-between">
                    <CardTitle>Activity Log</CardTitle>
                    <Dialog open={isActivityDialogOpen} onOpenChange={setIsActivityDialogOpen}>
                      <DialogTrigger asChild><Button size="sm"><Plus className="mr-2 h-4 w-4" />Log Activity</Button></DialogTrigger>
                      <DialogContent>
                        <DialogHeader><DialogTitle>Log Activity</DialogTitle><DialogDescription>Record a call, note, or other activity.</DialogDescription></DialogHeader>
                        <form onSubmit={handleAddActivity} className="space-y-4">
                          <div><Label>Activity Type</Label>
                            <Select value={activityFormData.type} onValueChange={(value) => setActivityFormData({ ...activityFormData, type: value })}>
                              <SelectTrigger><SelectValue /></SelectTrigger>
                              <SelectContent>
                                <SelectItem value="CALL">Phone Call</SelectItem>
                                <SelectItem value="NOTE">Note</SelectItem>
                                <SelectItem value="EMAIL">Email</SelectItem>
                                <SelectItem value="VISIT">Visit</SelectItem>
                                <SelectItem value="SMS">SMS</SelectItem>
                                <SelectItem value="OTHER">Other</SelectItem>
                              </SelectContent>
                            </Select>
                          </div>
                          <div><Label>Description</Label><Textarea value={activityFormData.description} onChange={(e) => setActivityFormData({ ...activityFormData, description: e.target.value })} required placeholder="Describe the activity..." /></div>
                          <div><Label>Contact Number</Label><Input value={activityFormData.contactNumber} onChange={(e) => setActivityFormData({ ...activityFormData, contactNumber: e.target.value })} placeholder="Phone number contacted" /></div>
                          <div><Label>Outcome</Label><Input value={activityFormData.outcome} onChange={(e) => setActivityFormData({ ...activityFormData, outcome: e.target.value })} placeholder="e.g., Promised to pay, No answer" /></div>
                          <div><Label>Date</Label><Input type="date" value={activityFormData.activityDate} onChange={(e) => setActivityFormData({ ...activityFormData, activityDate: e.target.value })} required /></div>
                          <Button type="submit" className="w-full">Log Activity</Button>
                        </form>
                      </DialogContent>
                    </Dialog>
                  </CardHeader>
                  <CardContent>
                    {activities.length === 0 ? (<p className="text-gray-500 text-center py-4">No activities logged yet.</p>) : (
                      <div className="space-y-4">
                        {activities.map((activity) => (
                          <div key={activity.id} className="flex gap-4 p-4 bg-gray-50 rounded-lg">
                            <div className="flex-shrink-0 w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center text-blue-600">
                              {getActivityIcon(activity.type)}
                            </div>
                            <div className="flex-1">
                              <div className="flex items-center gap-2">
                                <Badge variant="outline">{activity.type}</Badge>
                                <span className="text-sm text-gray-500">{formatDate(activity.activityDate)}</span>
                                <span className="text-sm text-gray-500">by {activity.user.name}</span>
                              </div>
                              <p className="mt-1 text-gray-700">{activity.description}</p>
                              {activity.outcome && (<p className="mt-1 text-sm text-gray-600"><strong>Outcome:</strong> {activity.outcome}</p>)}
                            </div>
                          </div>
                        ))}
                      </div>
                    )}
                  </CardContent>
                </Card>
              </TabsContent>

              <TabsContent value="promises">
                <Card>
                  <CardHeader className="flex flex-row items-center justify-between">
                    <CardTitle>Promise to Pay</CardTitle>
                    <Dialog open={isPromiseDialogOpen} onOpenChange={setIsPromiseDialogOpen}>
                      <DialogTrigger asChild><Button size="sm"><Plus className="mr-2 h-4 w-4" />Add Promise</Button></DialogTrigger>
                      <DialogContent>
                        <DialogHeader><DialogTitle>Record Promise to Pay</DialogTitle><DialogDescription>Record a customer&apos;s commitment to pay.</DialogDescription></DialogHeader>
                        <form onSubmit={handleAddPromise} className="space-y-4">
                          <div><Label>Promised Amount (KES)</Label><Input type="number" step="0.01" value={promiseFormData.promisedAmount} onChange={(e) => setPromiseFormData({ ...promiseFormData, promisedAmount: e.target.value })} required /></div>
                          <div><Label>Promised Date</Label><Input type="date" value={promiseFormData.promisedDate} onChange={(e) => setPromiseFormData({ ...promiseFormData, promisedDate: e.target.value })} required /></div>
                          <div><Label>Follow-up Date</Label><Input type="date" value={promiseFormData.followUpDate} onChange={(e) => setPromiseFormData({ ...promiseFormData, followUpDate: e.target.value })} /></div>
                          <div><Label>Notes</Label><Textarea value={promiseFormData.notes} onChange={(e) => setPromiseFormData({ ...promiseFormData, notes: e.target.value })} /></div>
                          <Button type="submit" className="w-full">Record Promise</Button>
                        </form>
                      </DialogContent>
                    </Dialog>
                  </CardHeader>
                  <CardContent>
                    {promises.length === 0 ? (<p className="text-gray-500 text-center py-4">No promises recorded yet.</p>) : (
                      <div className="space-y-4">
                        {promises.map((promise) => (
                          <div key={promise.id} className="p-4 border rounded-lg">
                            <div className="flex items-center justify-between">
                              <div>
                                <p className="font-semibold">{formatCurrency(promise.promisedAmount)}</p>
                                <p className="text-sm text-gray-500">Due: {formatDate(promise.promisedDate)}</p>
                                {promise.followUpDate && (<p className="text-sm text-gray-500">Follow-up: {formatDate(promise.followUpDate)}</p>)}
                              </div>
                              <div className="flex items-center gap-2">
                                <Badge className={getPromiseStatusColor(promise.status)}>{promise.status}</Badge>
                              </div>
                            </div>
                            {promise.notes && (<p className="mt-2 text-sm text-gray-600">{promise.notes}</p>)}
                            {promise.status === "PENDING" && (
                              <div className="mt-3 flex gap-2">
                                <Button size="sm" variant="outline" onClick={() => handleUpdatePromiseStatus(promise.id, "KEPT")} className="text-green-600"><CheckCircle className="mr-1 h-4 w-4" />Kept</Button>
                                <Button size="sm" variant="outline" onClick={() => handleUpdatePromiseStatus(promise.id, "BROKEN")} className="text-red-600"><XCircle className="mr-1 h-4 w-4" />Broken</Button>
                                <Button size="sm" variant="outline" onClick={() => handleUpdatePromiseStatus(promise.id, "RESCHEDULED")} className="text-blue-600"><Clock className="mr-1 h-4 w-4" />Rescheduled</Button>
                              </div>
                            )}
                          </div>
                        ))}
                      </div>
                    )}
                  </CardContent>
                </Card>
              </TabsContent>

              <TabsContent value="timeline">
                <Card>
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <CardTitle className="flex items-center gap-2">
                        <History className="h-5 w-5" />
                        Communication Timeline
                      </CardTitle>
                      <div className="flex items-center gap-4 text-sm">
                        <span className="flex items-center gap-1">
                          <Phone className="h-4 w-4 text-blue-600" />
                          {timelineStats.totalCalls} calls
                        </span>
                        <span className="flex items-center gap-1">
                          <MessageSquare className="h-4 w-4 text-green-600" />
                          {timelineStats.totalSms} SMS
                        </span>
                        <span className="flex items-center gap-1">
                          <Banknote className="h-4 w-4 text-purple-600" />
                          {timelineStats.totalPayments} payments
                        </span>
                        {timelineStats.inboundMessages > 0 && (
                          <Badge className="bg-orange-100 text-orange-800">
                            {timelineStats.inboundMessages} unread
                          </Badge>
                        )}
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent>
                    {timeline.length === 0 ? (
                      <p className="text-gray-500 text-center py-8">No communications recorded yet.</p>
                    ) : (
                      <div className="space-y-4">
                        {timeline.map((item) => {
                          const getIcon = () => {
                            if (item.channel === "CALL") return <Phone className="h-4 w-4" />;
                            if (item.channel === "SMS") return <MessageSquare className="h-4 w-4" />;
                            if (item.channel === "EMAIL") return <Mail className="h-4 w-4" />;
                            if (item.channel === "PAYMENT") return <Banknote className="h-4 w-4" />;
                            if (item.channel === "PROMISE") return <Calendar className="h-4 w-4" />;
                            return <FileText className="h-4 w-4" />;
                          };

                          const getIconBg = () => {
                            if (item.direction === "INBOUND") return "bg-green-100 text-green-600";
                            if (item.channel === "PAYMENT") return "bg-purple-100 text-purple-600";
                            if (item.channel === "PROMISE") return "bg-yellow-100 text-yellow-600";
                            return "bg-blue-100 text-blue-600";
                          };

                          return (
                            <div key={item.id} className="flex items-start gap-4 p-3 border rounded-lg hover:bg-gray-50">
                              <div className={`p-2 rounded-full ${getIconBg()}`}>
                                {getIcon()}
                              </div>
                              <div className="flex-1 min-w-0">
                                <div className="flex items-center gap-2">
                                  <span className="font-medium">{item.channel}</span>
                                  {item.direction === "INBOUND" ? (
                                    <ArrowDownLeft className="h-4 w-4 text-green-600" />
                                  ) : (
                                    <ArrowUpRight className="h-4 w-4 text-blue-600" />
                                  )}
                                  <span className="text-xs text-gray-500">{item.direction}</span>
                                  {item.isAutomated && (
                                    <Badge variant="outline" className="text-xs">Auto</Badge>
                                  )}
                                </div>
                                <p className="text-sm text-gray-600 mt-1">{item.content}</p>
                                <div className="flex items-center gap-4 mt-2 text-xs text-gray-500">
                                  <span className="flex items-center gap-1">
                                    <Clock className="h-3 w-3" />
                                    {new Date(item.createdAt).toLocaleString()}
                                  </span>
                                  {item.createdBy && (
                                    <span>by {item.createdBy}</span>
                                  )}
                                  {item.duration && (
                                    <span>{Math.floor(item.duration / 60)}:{(item.duration % 60).toString().padStart(2, "0")} min</span>
                                  )}
                                  {item.amount && (
                                    <span className="font-medium text-green-600">
                                      KES {item.amount.toLocaleString()}
                                    </span>
                                  )}
                                </div>
                              </div>
                              <div>
                                {item.status === "COMPLETED" || item.status === "KEPT" ? (
                                  <CheckCircle className="h-5 w-5 text-green-500" />
                                ) : item.status === "FAILED" || item.status === "BROKEN" ? (
                                  <XCircle className="h-5 w-5 text-red-500" />
                                ) : item.status === "PENDING" || item.status === "RESCHEDULED" ? (
                                  <Clock className="h-5 w-5 text-yellow-500" />
                                ) : (
                                  <Badge variant="outline" className="text-xs">{item.status}</Badge>
                                )}
                              </div>
                            </div>
                          );
                        })}
                      </div>
                    )}
                  </CardContent>
                </Card>
              </TabsContent>
            </Tabs>
          </div>

          {/* Right Column - Summary */}
          <div className="space-y-6">
            <Card>
              <CardHeader><CardTitle>Financial Summary</CardTitle></CardHeader>
              <CardContent className="space-y-3">
                <div className="flex justify-between"><span className="text-gray-500">Applied Amount:</span><span className="font-medium">{formatCurrency(file?.appliedAmount ?? 0)}</span></div>
                <div className="flex justify-between"><span className="text-gray-500">Allocated Amount:</span><span className="font-medium">{formatCurrency(file?.allocatedAmount ?? 0)}</span></div>
                <div className="flex justify-between"><span className="text-gray-500">Commission (10%):</span><span className="font-medium">{formatCurrency(file?.commission ?? 0)}</span></div>
                <div className="flex justify-between"><span className="text-gray-500">VAT (16%):</span><span className="font-medium">{formatCurrency(file?.vat ?? 0)}</span></div>
                <hr />
                <div className="flex justify-between text-lg"><span className="font-semibold">Total to Collect:</span><span className="font-bold">{formatCurrency(file?.totalToCollect ?? 0)}</span></div>
                <div className="flex justify-between text-lg"><span className="font-semibold text-red-600">Outstanding:</span><span className="font-bold text-red-600">{formatCurrency(file?.outstandingBalance ?? 0)}</span></div>
                <div className="flex justify-between"><span className="text-gray-500">Collected:</span><span className="font-medium text-green-600">{formatCurrency((file?.totalToCollect ?? 0) - (file?.outstandingBalance ?? 0))}</span></div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader><CardTitle>Collection Progress</CardTitle></CardHeader>
              <CardContent>
                <div className="space-y-2">
                  <div className="flex justify-between text-sm"><span>Progress</span><span>{Math.round((((file?.totalToCollect ?? 0) - (file?.outstandingBalance ?? 0)) / (file?.totalToCollect || 1)) * 100)}%</span></div>
                  <div className="w-full bg-gray-200 rounded-full h-3">
                    <div className="bg-green-500 h-3 rounded-full" style={{ width: `${Math.min(100, Math.round((((file?.totalToCollect ?? 0) - (file?.outstandingBalance ?? 0)) / (file?.totalToCollect || 1)) * 100))}%` }}></div>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* AI Insights Panel */}
            <Card className="border-purple-200 bg-gradient-to-br from-purple-50 to-white">
              <CardHeader className="pb-2">
                <div className="flex items-center justify-between">
                  <CardTitle className="flex items-center gap-2 text-purple-700">
                    <Brain className="h-5 w-5" />
                    AI Insights
                  </CardTitle>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => fetchAiPrediction(true)}
                    disabled={isLoadingAi}
                    className="text-purple-600 hover:text-purple-800"
                  >
                    <RefreshCw className={`h-4 w-4 ${isLoadingAi ? 'animate-spin' : ''}`} />
                  </Button>
                </div>
              </CardHeader>
              <CardContent className="space-y-4">
                {isLoadingAi ? (
                  <div className="flex items-center justify-center py-8">
                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600"></div>
                    <span className="ml-2 text-gray-500">Analyzing...</span>
                  </div>
                ) : aiPrediction ? (
                  <>
                    {/* Payment Probability */}
                    <div className="space-y-2">
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium flex items-center gap-1">
                          <TrendingUp className="h-4 w-4 text-purple-500" />
                          Payment Probability
                        </span>
                        <Badge className={`${
                          aiPrediction.paymentProbability >= 70 ? 'bg-green-100 text-green-800' :
                          aiPrediction.paymentProbability >= 40 ? 'bg-yellow-100 text-yellow-800' :
                          'bg-red-100 text-red-800'
                        }`}>
                          {aiPrediction.paymentProbability}%
                        </Badge>
                      </div>
                      <div className="w-full bg-gray-200 rounded-full h-2">
                        <div
                          className={`h-2 rounded-full ${
                            aiPrediction.paymentProbability >= 70 ? 'bg-green-500' :
                            aiPrediction.paymentProbability >= 40 ? 'bg-yellow-500' :
                            'bg-red-500'
                          }`}
                          style={{ width: `${aiPrediction.paymentProbability}%` }}
                        ></div>
                      </div>
                    </div>

                    {/* Risk Level */}
                    <div className="flex items-center justify-between py-2 border-t border-b">
                      <span className="text-sm font-medium flex items-center gap-1">
                        <AlertTriangle className="h-4 w-4 text-orange-500" />
                        Risk Level
                      </span>
                      <Badge variant={
                        aiPrediction.riskLevel === 'LOW' ? 'default' :
                        aiPrediction.riskLevel === 'MEDIUM' ? 'secondary' : 'destructive'
                      }>
                        {aiPrediction.riskLevel}
                      </Badge>
                    </div>

                    {/* Optimal Engagement */}
                    {(aiPrediction.optimalChannel || aiPrediction.optimalTimeSlot) && (
                      <div className="bg-blue-50 p-3 rounded-lg space-y-2">
                        <span className="text-sm font-medium text-blue-800 flex items-center gap-1">
                          <Target className="h-4 w-4" />
                          Optimal Engagement
                        </span>
                        <div className="grid grid-cols-2 gap-2 text-xs">
                          {aiPrediction.optimalChannel && (
                            <div className="bg-white p-2 rounded">
                              <span className="text-gray-500">Channel:</span>
                              <div className="font-medium">{aiPrediction.optimalChannel}</div>
                            </div>
                          )}
                          {aiPrediction.optimalTimeSlot && (
                            <div className="bg-white p-2 rounded">
                              <span className="text-gray-500">Time:</span>
                              <div className="font-medium">{aiPrediction.optimalTimeSlot}</div>
                            </div>
                          )}
                          {aiPrediction.optimalDayOfWeek && (
                            <div className="bg-white p-2 rounded col-span-2">
                              <span className="text-gray-500">Best Day:</span>
                              <div className="font-medium">{aiPrediction.optimalDayOfWeek}</div>
                            </div>
                          )}
                        </div>
                      </div>
                    )}

                    {/* Next Best Action */}
                    <div className="bg-green-50 p-3 rounded-lg">
                      <span className="text-sm font-medium text-green-800 flex items-center gap-1 mb-1">
                        <Target className="h-4 w-4" />
                        Recommended Action
                      </span>
                      <p className="text-sm text-green-700">{aiPrediction.nextBestAction}</p>
                    </div>

                    {/* Key Insights */}
                    {aiPrediction.keyInsights && aiPrediction.keyInsights.length > 0 && (
                      <div className="space-y-2">
                        <span className="text-sm font-medium flex items-center gap-1">
                          <Lightbulb className="h-4 w-4 text-yellow-500" />
                          Key Insights
                        </span>
                        <ul className="text-xs space-y-1">
                          {aiPrediction.keyInsights.map((insight, index) => (
                            <li key={index} className="flex items-start gap-2 text-gray-600">
                              <span className="text-purple-500 mt-0.5">•</span>
                              {insight}
                            </li>
                          ))}
                        </ul>
                      </div>
                    )}

                    {/* Patterns Detected */}
                    {aiPrediction.patterns && aiPrediction.patterns.length > 0 && (
                      <div className="bg-gray-50 p-3 rounded-lg">
                        <span className="text-xs font-medium text-gray-600 mb-1 block">Patterns Detected</span>
                        <div className="flex flex-wrap gap-1">
                          {aiPrediction.patterns.map((pattern, index) => (
                            <Badge key={index} variant="outline" className="text-xs">
                              {pattern}
                            </Badge>
                          ))}
                        </div>
                      </div>
                    )}

                    {/* Confidence & Feedback */}
                    <div className="flex items-center justify-between pt-2 border-t">
                      <span className="text-xs text-gray-500">
                        Confidence: {Math.round(aiPrediction.confidence * 100)}%
                      </span>
                      <Button
                        variant="outline"
                        size="sm"
                        className="text-xs"
                        onClick={() => setIsFeedbackDialogOpen(true)}
                      >
                        Record Outcome
                      </Button>
                    </div>
                  </>
                ) : (
                  <div className="text-center py-4 text-gray-500">
                    <Brain className="h-8 w-8 mx-auto mb-2 opacity-50" />
                    <p className="text-sm">Click refresh to generate AI insights</p>
                  </div>
                )}
              </CardContent>
            </Card>

            {/* AI Feedback Dialog */}
            <Dialog open={isFeedbackDialogOpen} onOpenChange={setIsFeedbackDialogOpen}>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle className="flex items-center gap-2">
                    <Brain className="h-5 w-5 text-purple-600" />
                    Record Action Outcome
                  </DialogTitle>
                  <DialogDescription>
                    Help the AI learn by recording the outcome of your action
                  </DialogDescription>
                </DialogHeader>
                <div className="space-y-4">
                  <div>
                    <Label>Action Taken</Label>
                    <Select
                      value={feedbackData.actionTaken}
                      onValueChange={(value) => setFeedbackData({ ...feedbackData, actionTaken: value })}
                    >
                      <SelectTrigger><SelectValue placeholder="Select action" /></SelectTrigger>
                      <SelectContent>
                        <SelectItem value="CALL">Phone Call</SelectItem>
                        <SelectItem value="SMS">SMS Message</SelectItem>
                        <SelectItem value="EMAIL">Email</SelectItem>
                        <SelectItem value="VISIT">Physical Visit</SelectItem>
                        <SelectItem value="OTHER">Other</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label>Outcome</Label>
                    <Select
                      value={feedbackData.actionOutcome}
                      onValueChange={(value) => setFeedbackData({ ...feedbackData, actionOutcome: value })}
                    >
                      <SelectTrigger><SelectValue placeholder="Select outcome" /></SelectTrigger>
                      <SelectContent>
                        <SelectItem value="SUCCESS">
                          <div className="flex items-center gap-2">
                            <ThumbsUp className="h-4 w-4 text-green-500" />
                            Success - Payment received
                          </div>
                        </SelectItem>
                        <SelectItem value="PARTIAL">
                          <div className="flex items-center gap-2">
                            <CheckCircle className="h-4 w-4 text-yellow-500" />
                            Partial - Promise to pay
                          </div>
                        </SelectItem>
                        <SelectItem value="FAILED">
                          <div className="flex items-center gap-2">
                            <ThumbsDown className="h-4 w-4 text-red-500" />
                            Failed - Refused to pay
                          </div>
                        </SelectItem>
                        <SelectItem value="NO_RESPONSE">
                          <div className="flex items-center gap-2">
                            <XCircle className="h-4 w-4 text-gray-500" />
                            No Response
                          </div>
                        </SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label>Notes (optional)</Label>
                    <Textarea
                      value={feedbackData.notes}
                      onChange={(e) => setFeedbackData({ ...feedbackData, notes: e.target.value })}
                      placeholder="Any additional details..."
                      rows={3}
                    />
                  </div>
                  <div className="flex gap-2">
                    <Button onClick={handleSubmitFeedback} className="flex-1 bg-purple-600 hover:bg-purple-700">
                      Submit Feedback
                    </Button>
                    <Button variant="outline" onClick={() => setIsFeedbackDialogOpen(false)}>
                      Cancel
                    </Button>
                  </div>
                </div>
              </DialogContent>
            </Dialog>

            {/* M-Pesa STK Push Dialog */}
            <Dialog open={isMpesaDialogOpen} onOpenChange={setIsMpesaDialogOpen}>
              <DialogContent className="sm:max-w-md">
                <DialogHeader>
                  <DialogTitle className="flex items-center gap-2">
                    <Smartphone className="h-5 w-5 text-green-600" />
                    Send M-Pesa Payment Request
                  </DialogTitle>
                  <DialogDescription>
                    Send an STK Push to the customer&apos;s phone. They will enter their M-Pesa PIN to complete payment.
                  </DialogDescription>
                </DialogHeader>
                <form onSubmit={handleInitiateMpesa} className="space-y-4 pt-4">
                  {pendingMpesaTxId && (
                    <div className="bg-blue-50 border border-blue-200 rounded-lg p-3 flex items-center gap-2">
                      <Loader2 className="h-4 w-4 text-blue-600 animate-spin" />
                      <span className="text-sm text-blue-800">Waiting for customer to complete payment...</span>
                    </div>
                  )}
                  <div>
                    <Label htmlFor="mpesa-phone">Phone Number</Label>
                    <Input
                      id="mpesa-phone"
                      value={mpesaFormData.phoneNumber}
                      onChange={(e) => setMpesaFormData({ ...mpesaFormData, phoneNumber: e.target.value })}
                      placeholder="254712345678"
                      required
                    />
                    <p className="text-xs text-muted-foreground mt-1">Format: 254XXXXXXXXX or 07XXXXXXXX</p>
                  </div>
                  <div>
                    <Label htmlFor="mpesa-amount">Amount (KES)</Label>
                    <Input
                      id="mpesa-amount"
                      type="number"
                      value={mpesaFormData.amount}
                      onChange={(e) => setMpesaFormData({ ...mpesaFormData, amount: e.target.value })}
                      placeholder="Enter amount"
                      required
                      min="1"
                    />
                    {file && (
                      <p className="text-xs text-muted-foreground mt-1">
                        Outstanding balance: KES {file.outstandingBalance.toLocaleString()}
                      </p>
                    )}
                  </div>
                  <div className="flex gap-2 pt-2">
                    <Button
                      type="submit"
                      disabled={isInitiatingMpesa || !!pendingMpesaTxId}
                      className="flex-1 bg-green-600 hover:bg-green-700"
                    >
                      {isInitiatingMpesa ? (
                        <>
                          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                          Sending...
                        </>
                      ) : (
                        <>
                          <Send className="mr-2 h-4 w-4" />
                          Send Request
                        </>
                      )}
                    </Button>
                    <Button type="button" variant="outline" onClick={() => setIsMpesaDialogOpen(false)}>
                      Cancel
                    </Button>
                  </div>
                </form>
              </DialogContent>
            </Dialog>
          </div>
        </div>
      </div>
    </ProtectedLayout>
  );
}
