"use client"

import { useState, useEffect } from "react"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Progress } from "@/components/ui/progress"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import {
  ArrowLeft,
  DollarSign,
  Calendar,
  User,
  Phone,
  Mail,
  MapPin,
  CreditCard,
  AlertTriangle,
  CheckCircle,
  Clock,
  TrendingUp,
  FileText,
} from "lucide-react"
import Link from "next/link"
import { EditLoanModal } from "./modals/edit-loan-modal"
import { LoanQuickActions } from "./loan-quick-actions"
import https from "@/services/https";
import { ReplaceDeviceModal } from "./modals/replace-device-modal";
import { QuickRecordPayment } from "./quick-record-payment"

export default function LoanDetailPage({ loanId }) {
  const [loan, setLoan] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const [isAgreementModalOpen, setIsAgreementModalOpen] = useState(false);
  const [isGeneratingAccount, setIsGeneratingAccount] = useState(false);

  const fetchLoanData = async () => {
    setIsLoading(true);
    try {
      const token = localStorage.getItem("token");
      const response = await fetch(`${https.baseUrl}/loans/${loanId}`, {
        headers: {
          "x-auth-token": token,
        },
      });
      if (!response.ok) {
        throw new Error("Failed to fetch loan data");
      }
      const data = await response.json();
      setLoan(data);
    } catch (err) {
      setError(err.message);
      console.error("Error fetching loan:", err);
    } finally {
      setIsLoading(false);
    }
  };

  const [userRole, setUserRole] = useState(null);

  useEffect(() => {
    const token = localStorage.getItem("token");
    if (token) {
      try {
        const decodedToken = JSON.parse(atob(token.split('.')[1])); // Decode JWT payload
        setUserRole(decodedToken.user.role);
      } catch (e) {
        console.error("Error decoding token:", e);
      }
    }
    if (loanId) {
      fetchLoanData();
    }
  }, [loanId]);

  const handleLoanAction = async (action) => {
    setIsLoading(true);
    try {
      const token = localStorage.getItem("token");
      let url = `${https.baseUrl}/loans/${loanId}`;
      let method = "PUT";
      let body = {};

      if (action === "approve") {
        url += "/approve";
      } else if (action === "reject") {
        // Assuming a reject endpoint or status update
        url = `${https.baseUrl}/loans/${loanId}`;
        body = { status: "rejected" }; // Or whatever status indicates rejection
      } else if (action === "pause") {
        url += "/pause";
      } else if (action === "resume") {
        url += "/resume";
      }

      const response = await fetch(url, {
        method: method,
        headers: {
          "Content-Type": "application/json",
          "x-auth-token": token,
        },
        body: Object.keys(body).length > 0 ? JSON.stringify(body) : undefined,
      });

      if (!response.ok) {
        throw new Error(`Failed to ${action} loan`);
      }

      // Refresh loan data after successful action
      await fetchLoanData();
    } catch (err) {
      setError(err.message);
      console.error(`Error ${action}ing loan:`, err);
    } finally {
      setIsLoading(false);
    }
  };

  const handleViewAgreement = () => {
    if (loan.signedAgreement) {
      setIsAgreementModalOpen(true);
    }
  };

  const handleDownloadAgreement = () => {
    if (loan.signedAgreement) {
      const link = document.createElement('a');
      link.href = `data:image/jpeg;base64,${loan.signedAgreement}`;
      link.download = `signed_agreement_${loan.loan_id}.jpg`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  };

  const generateAccountNumber = async () => {
    setIsGeneratingAccount(true);
    try {
      const token = localStorage.getItem("token");
      const response = await fetch(`${https.baseUrl}/loans/${loanId}/dedicated-account`, {
        method: 'POST',
        headers: {
          "x-auth-token": token,
        },
      });
      if (!response.ok) {
        throw new Error("Failed to generate account number");
      }
      // Refresh loan data to get the new account number
      fetchLoanData();
    } catch (err) {
      setError(err.message);
      console.error("Error generating account number:", err);
    } finally {
      setIsGeneratingAccount(false);
    }
  };

  if (isLoading || !loan) {
    return <div>Loading loan data...</div>;
  }

  if (error) {
    return <div>Error: {error}</div>;
  }

  const loanProgress = parseFloat(loan.progress) || 0;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <Link href="/loans">
            <Button className="bg-brand-primary text-white hover:bg-brand-primary/80" size="sm">
              <ArrowLeft className="mr-2 h-4 w-4" />
              Back to Loans
            </Button>
          </Link>
          <div>
            <h1 className="text-3xl font-bold">Loan {loan.loan_id}</h1>
            <p className="text-muted-foreground">{loan.customer_name}</p>
          </div>
        </div>
        <div className="flex items-center space-x-2">
          <Badge
            variant={
              loan.status === "active"
                ? "default"
                : loan.status === "defaulted"
                  ? "destructive"
                  : loan.status === "pending" || loan.status === "paused"
                    ? "warning"
                    : "secondary"
            }
          >
            {loan.status}
            {/* {loan.loanDetails.daysOverdue > 0 && ` (${loan.loanDetails.daysOverdue}d overdue)`} */}
          </Badge>
          <EditLoanModal loan={loan} onUpdate={fetchLoanData} />
          {loan.status === "pending" && userRole === "admin" && (
            <>
              <Button className="bg-green-500 text-white hover:bg-green-600" onClick={() => handleLoanAction("approve")}>
                <CheckCircle className="mr-2 h-4 w-4" />
                Approve Loan
              </Button>
              <Button className="bg-red-500 text-white hover:bg-red-600" onClick={() => handleLoanAction("reject")}>
                <AlertTriangle className="mr-2 h-4 w-4" />
                Reject Loan
              </Button>
            </>
          )}
          {loan.status === "active" && (
            <Button className="bg-yellow-500 text-white hover:bg-yellow-600" onClick={() => handleLoanAction("pause")}>
              <Clock className="mr-2 h-4 w-4" />
              Pause Loan
            </Button>
          )}
          {loan.status === "paused" && (
            <Button className="bg-green-500 text-white hover:bg-green-600" onClick={() => handleLoanAction("resume")}>
              <CheckCircle className="mr-2 h-4 w-4" />
              Resume Loan
            </Button>
          )}
        </div>
      </div>

      {/* Loan Status Cards */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card className="shadow-md rounded-lg border hover:shadow-lg transition-shadow">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Loan Progress</CardTitle>
            <TrendingUp className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">{parseFloat(loanProgress).toFixed(1)}%</div>
            <Progress value={loanProgress} className="mt-2" />
            <p className="text-xs text-muted-foreground mt-1">
              NGN { parseFloat(loan?.remainingAmount)?.toLocaleString()} remaining
            </p>
          </CardContent>
        </Card>
 
        <Card className="shadow-md rounded-lg border hover:shadow-lg transition-shadow">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Amount Paid</CardTitle>
            <DollarSign className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">NGN {parseFloat(loan.paidAmount).toLocaleString()}</div>
            <p className="text-xs text-muted-foreground">of NGN {parseFloat(loan.totalAmount).toLocaleString()}</p>
          </CardContent>
        </Card>

        <Card className="shadow-md rounded-lg border hover:shadow-lg transition-shadow">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Next Payment</CardTitle>
            <Calendar className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-blue-600">NGN {parseFloat(loan?.paymentAmountPerCycle)?.toLocaleString()}</div>
            <p className="text-xs text-muted-foreground">Due: {new Date(loan.nextPaymentDate).toLocaleDateString()}</p>
          </CardContent>
        </Card>

        <Card className="shadow-md rounded-lg border hover:shadow-lg transition-shadow">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Credit Score</CardTitle>
            <CreditCard className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{loan.customer.creditScore}</div>
            <p className="text-xs text-muted-foreground">
              {loan.customer.creditScore >= 80 ? "Excellent" : loan.customer.creditScore >= 60 ? "Good" : "Poor"}
            </p>
          </CardContent>
        </Card>
      </div>

      {/* Main Content */}
      <div className="grid gap-6 md:grid-cols-3">
        <div className="md:col-span-2">
          <Tabs defaultValue="overview" className="space-y-4">
            <TabsList>
              <TabsTrigger value="overview" className="data-[state=active]:bg-brand-primary data-[state=active]:text-white data-[state=inactive]:bg-transparent data-[state=inactive]:text-gray-500 data-[state=inactive]:hover:bg-gray-200 transition-colors">Overview</TabsTrigger>
              <TabsTrigger value="payments" className="data-[state=active]:bg-brand-primary data-[state=active]:text-white data-[state=inactive]:bg-transparent data-[state=inactive]:text-gray-500 data-[state=inactive]:hover:bg-gray-200 transition-colors">Payments</TabsTrigger>
              <TabsTrigger value="schedule" className="data-[state=active]:bg-brand-primary data-[state=active]:text-white data-[state=inactive]:bg-transparent data-[state=inactive]:text-gray-500 data-[state=inactive]:hover:bg-gray-200 transition-colors">Schedule</TabsTrigger>
              <TabsTrigger value="activities" className="data-[state=active]:bg-brand-primary data-[state=active]:text-white data-[state=inactive]:bg-transparent data-[state=inactive]:text-gray-500 data-[state=inactive]:hover:bg-gray-200 transition-colors">Activities</TabsTrigger>
            </TabsList>

            <TabsContent value="overview" className="space-y-4">
              <div className="grid gap-4 md:grid-cols-2">
                <Card className="shadow-md rounded-lg border hover:shadow-lg transition-shadow">
                  <CardHeader>
                    <CardTitle>Loan Details</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <div className="flex justify-between">
                      <span className="text-sm text-blue-900">Principal Amount:</span>
                      <span className="text-sm font-medium text-blue-700">
                        NGN {parseFloat(loan.totalAmount).toLocaleString()}
                      </span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-sm text-blue-900">Interest Rate:</span>
                      <span className="text-sm font-medium text-blue-700">{/* loan.loanDetails.interestRate */}N/A</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-sm text-blue-900">Term:</span>
                      <span className="text-sm font-medium text-blue-700">{loan.termMonths} months</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-sm text-blue-900">Monthly Payment:</span>
                      <span className="text-sm font-medium text-blue-700">
                        NGN {parseFloat(loan?.paymentAmountPerCycle)?.toLocaleString()}
                      </span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-sm text-blue-900">Start Date:</span>
                      <span className="text-sm font-medium text-blue-700">{new Date(loan.startDate).toLocaleDateString()}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-sm text-blue-900">End Date:</span>
                      <span className="text-sm font-medium text-blue-700">{new Date(new Date(loan.startDate).setMonth(new Date(loan.startDate).getMonth() + loan.termMonths)).toLocaleDateString()}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-sm text-blue-900">Guarantor:</span>
                      <span className="text-sm font-medium text-blue-700">
                        {loan.guarantorDetails ? loan.guarantorDetails.name : "N/A"}
                      </span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-sm text-blue-900">Assigned Agent:</span>
                      <span className="text-sm font-medium text-blue-700">
                        {loan.agent ? loan.agent.username : "N/A"}
                      </span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-sm text-blue-900">Account Number:</span>
                      {loan.accountNumber ? (
                        <span className="text-sm font-medium">{loan.accountNumber}</span>
                      ) : (
                        <Button onClick={generateAccountNumber} disabled={isGeneratingAccount} size="sm" className="bg-green-500 text-white hover:bg-green-600">
                          {isGeneratingAccount ? 'Generating...' : 'Generate'}
                        </Button>
                      )}
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-sm text-muted-foreground">Signed Agreement:</span>
                      {loan.signedAgreement ? (
                        <div>
                          <Button className="bg-brand-primary text-white hover:bg-brand-primary/80" size="sm" onClick={handleViewAgreement}>View</Button>
                          <Button className="bg-brand-primary text-white hover:bg-brand-primary/80 ml-2" size="sm" onClick={handleDownloadAgreement}>Download</Button>
                        </div>
                      ) : (
                        <span className="text-sm font-medium">N/A</span>
                      )}
                    </div>
                  </CardContent>
                </Card>

                <Card className="shadow-md rounded-lg border hover:shadow-lg transition-shadow">
                  <CardHeader>
                    <CardTitle>Customer Information</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div className="flex items-center space-x-4">
                      <div className="w-12 h-12 bg-gray-200 rounded-full flex items-center justify-center">
                        <User className="h-6 w-6 text-gray-500" />
                      </div>
                      <div>
                        <h3 className="font-medium text-blue-900">{loan.customer_name}</h3>
                        <p className="text-sm text-blue-700">{loan.customer.id}</p>
                      </div>
                    </div>

                    <div className="space-y-3">
                      <div className="flex items-center space-x-2">
                        <Phone className="h-4 w-4 text-blue-900" />
                        <span className="text-sm text-blue-700">{loan.customer.phone}</span>
                      </div>
                      <div className="flex items-center space-x-2">
                        <Mail className="h-4 w-4 text-blue-900" />
                        <span className="text-sm text-blue-700">{loan.customer.email}</span>
                      </div>
                      <div className="flex items-center space-x-2">
                        <MapPin className="h-4 w-4 text-blue-900" />
                        <span className="text-sm text-blue-700">{loan.customer.location}</span>
                      </div>
                      <div className="flex items-center space-x-2">
                        <FileText className="h-4 w-4 text-blue-900" />
                        <span className="text-sm text-blue-700">ID: {loan.customer.idNumber}</span>
                      </div>
                    </div>

                    <div className="pt-4 border-t">
                        <h4 className="font-medium mb-2 text-blue-900">Device Information</h4>
                        <div className="space-y-2">
                          <div className="flex justify-between">
                            <span className="text-sm text-blue-900">Device:</span>
                            <span className="text-sm font-medium text-blue-700">{loan.device.type}</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-sm text-blue-900">Model:</span>
                            <span className="text-sm font-medium text-blue-700">{loan.device.model}</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-sm text-blue-900">Serial:</span>
                            <span className="text-sm font-medium text-blue-700">{loan.device.serialNumber}</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-sm text-blue-900">Status:</span>
                            <Badge variant={loan.device.status === "Active" ? "success" : "destructive"}>
                              {loan.device.status}
                            </Badge>
                          </div>
                          <div className="flex justify-between items-center pt-2 mt-2 border-t">
                            <span className="text-sm text-blue-900">Actions:</span>
                            <ReplaceDeviceModal oldDeviceId={loan.device.id} onDeviceReplaced={fetchLoanData} />
                          </div>
                        </div>
                      </div>
                  </CardContent>
                </Card>
              </div>
            </TabsContent>

            <TabsContent value="payments" className="space-y-4">
              <Card className="shadow-md rounded-lg border hover:shadow-lg transition-shadow">
                <CardHeader>
                  <CardTitle>Payment History</CardTitle>
                </CardHeader>
                <CardContent>
                  <Table>
                    <TableHeader className="bg-gray-100">
                      <TableRow>
                        <TableHead>Date</TableHead>
                        <TableHead>Amount</TableHead>
                        <TableHead>Method</TableHead>
                        <TableHead>Reference</TableHead>
                        <TableHead>Status</TableHead>
                        {/* <TableHead>Late Fee</TableHead> */}
                      </TableRow>
                    </TableHeader>
                    <TableBody className="text-blue-900">
                      {loan.paymentHistory && loan.paymentHistory.map((payment) => (
                        <TableRow key={payment.id} className="hover:bg-gray-100 even:bg-gray-50">
                          <TableCell>{new Date(payment.created_at).toLocaleDateString()}</TableCell>
                          <TableCell className="text-blue-900">NGN {parseFloat(payment.amount).toLocaleString()}</TableCell>
                          <TableCell className="text-blue-700">{payment.payment_method}</TableCell>
                          <TableCell className="text-blue-500">{payment.transaction_id}</TableCell>
                          <TableCell>
                            <Badge variant={payment.status === "completed" ? "success" : "destructive"}>
                              {payment.status}
                            </Badge>
                          </TableCell>
                          {/* <TableCell>{payment.lateFee > 0 ? `NGN ${parseFloat(payment.lateFee).toLocaleString()}` : "-"}</TableCell> */}
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="schedule" className="space-y-4">
              <Card className="shadow-md rounded-lg border hover:shadow-lg transition-shadow">
                <CardHeader>
                  <CardTitle>Payment Schedule</CardTitle>
                </CardHeader>
                <CardContent>
                  <Table>
                    <TableHeader className="bg-gray-100">
                      <TableRow>
                        <TableHead>Installment</TableHead>
                        <TableHead>Due Date</TableHead>
                        <TableHead>Principal</TableHead>
                        <TableHead>Interest</TableHead>
                        <TableHead>Total</TableHead>
                        <TableHead>Status</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody className="text-blue-900">
                      {/* Loan schedule data is not directly available from the API in this format */}
                      <TableRow className="hover:bg-gray-100 even:bg-gray-50">
                        <TableCell colSpan="6" className="text-center text-muted-foreground">
                          Payment schedule not available.
                        </TableCell>
                      </TableRow>
                    </TableBody>
                  </Table>
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="activities" className="space-y-4">
              <Card className="shadow-md rounded-lg border hover:shadow-lg transition-shadow">
                <CardHeader>
                  <CardTitle>Recent Activities</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    {/* Activities data is not directly available from the API in this format */}
                    <div className="text-center text-muted-foreground">
                      No recent activities available.
                    </div>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>
          </Tabs>
        </div>

        {/* Quick Actions Sidebar */}
        <LoanQuickActions loan={loan} onAction={handleLoanAction} isLoading={isLoading} />
        {/* <QuickRecordPayment
          loan={loan}
          onPaymentRecorded={fetchLoanData}
          size="default"
          variant="default"
        /> */}
      </div>
      <Dialog open={isAgreementModalOpen} onOpenChange={setIsAgreementModalOpen}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle>Signed Agreement</DialogTitle>
          </DialogHeader>
          <img
            src={`data:image/jpeg;base64,${loan.signedAgreement}`}
            alt="Signed Agreement"
            className="w-full h-auto rounded-lg"
          />
        </DialogContent>
      </Dialog>
    </div>
  )
}

