import { useState, useEffect } from 'react'
import DashboardLayout from '@/components/layout/DashboardLayout'
import { Line, Bar, Doughnut } from 'react-chartjs-2'
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  ArcElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js'
import { format, subMonths } from 'date-fns'
import { GetServerSideProps } from 'next'
import { getServerSession } from 'next-auth'
import { authOptions } from '../api/auth/[...nextauth]'
import { Session } from 'next-auth'

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  ArcElement,
  Title,
  Tooltip,
  Legend
)

type ReportData = {
  disbursementTrend: {
    labels: string[]
    datasets: {
      label: string
      data: number[]
      borderColor: string
      tension: number
    }[]
  }
  loanStatusDistribution: {
    labels: string[]
    datasets: {
      data: number[]
      backgroundColor: string[]
    }[]
  }
  repaymentPerformance: {
    labels: string[]
    datasets: {
      label: string
      data: number[]
      backgroundColor: string
    }[]
  }
}

export const getServerSideProps: GetServerSideProps = async (context) => {
  const session = await getServerSession(context.req, context.res, authOptions)

  if (!session) {
    return {
      redirect: {
        destination: '/auth/signin',
        permanent: false,
      },
    }
  }

  return {
    props: {
      session,
    },
  }
}

interface ReportsProps {
  session: Session
}

export default function Reports({ session }: ReportsProps) {
  const [reportData, setReportData] = useState<ReportData>({
    disbursementTrend: {
      labels: [],
      datasets: [],
    },
    loanStatusDistribution: {
      labels: [],
      datasets: [],
    },
    repaymentPerformance: {
      labels: [],
      datasets: [],
    },
  })

  useEffect(() => {
    const fetchReportData = async () => {
      try {
        const res = await fetch('/api/reports')
        const data = await res.json()
        setReportData(data)
      } catch (error) {
        console.error('Error fetching report data:', error)
      }
    }

    fetchReportData()
  }, [])

  return (
    <DashboardLayout session={session}>
      <div className="min-h-screen py-8">
        <div className="mb-8">
          <h2 className="text-2xl font-bold leading-7 text-gray-900 sm:truncate sm:text-3xl sm:tracking-tight">
            Loan Reports
          </h2>
          <p className="mt-1 text-sm leading-6 text-gray-600">
            Comprehensive overview of loan performance and statistics
          </p>
        </div>

        <div className="grid grid-cols-1 gap-8 lg:grid-cols-2">
          {/* Disbursement Trend */}
          <div className="rounded-lg bg-white p-6 shadow">
            <h3 className="text-lg font-medium leading-6 text-gray-900">
              Loan Disbursement Trend
            </h3>
            <div className="mt-5 h-80">
              <Line
                data={reportData.disbursementTrend}
                options={{
                  responsive: true,
                  maintainAspectRatio: false,
                  plugins: {
                    legend: {
                      position: 'top' as const,
                    },
                  },
                }}
              />
            </div>
          </div>

          {/* Loan Status Distribution */}
          <div className="rounded-lg bg-white p-6 shadow">
            <h3 className="text-lg font-medium leading-6 text-gray-900">
              Loan Status Distribution
            </h3>
            <div className="mt-5 h-80">
              <Doughnut
                data={reportData.loanStatusDistribution}
                options={{
                  responsive: true,
                  maintainAspectRatio: false,
                  plugins: {
                    legend: {
                      position: 'right' as const,
                    },
                  },
                }}
              />
            </div>
          </div>

          {/* Repayment Performance */}
          <div className="col-span-full rounded-lg bg-white p-6 shadow">
            <h3 className="text-lg font-medium leading-6 text-gray-900">
              Repayment Performance
            </h3>
            <div className="mt-5 h-80">
              <Bar
                data={reportData.repaymentPerformance}
                options={{
                  responsive: true,
                  maintainAspectRatio: false,
                  plugins: {
                    legend: {
                      position: 'top' as const,
                    },
                  },
                  scales: {
                    y: {
                      beginAtZero: true,
                    },
                  },
                }}
              />
            </div>
          </div>

          {/* Summary Statistics */}
          <div className="col-span-full grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4">
            <div className="rounded-lg bg-white p-6 shadow">
              <h4 className="text-sm font-medium text-gray-500">
                Total Active Loans
              </h4>
              <p className="mt-2 text-3xl font-semibold text-gray-900">245</p>
              <p className="mt-2 text-sm text-gray-500">
                <span className="text-green-600">↑ 12%</span> vs last month
              </p>
            </div>

            <div className="rounded-lg bg-white p-6 shadow">
              <h4 className="text-sm font-medium text-gray-500">
                Total Disbursed Amount
              </h4>
              <p className="mt-2 text-3xl font-semibold text-gray-900">
                KES 12.5M
              </p>
              <p className="mt-2 text-sm text-gray-500">
                <span className="text-green-600">↑ 8%</span> vs last month
              </p>
            </div>

            <div className="rounded-lg bg-white p-6 shadow">
              <h4 className="text-sm font-medium text-gray-500">
                Average Loan Size
              </h4>
              <p className="mt-2 text-3xl font-semibold text-gray-900">
                KES 51,020
              </p>
              <p className="mt-2 text-sm text-gray-500">
                <span className="text-red-600">↓ 3%</span> vs last month
              </p>
            </div>

            <div className="rounded-lg bg-white p-6 shadow">
              <h4 className="text-sm font-medium text-gray-500">Default Rate</h4>
              <p className="mt-2 text-3xl font-semibold text-gray-900">2.3%</p>
              <p className="mt-2 text-sm text-gray-500">
                <span className="text-green-600">↓ 0.5%</span> vs last month
              </p>
            </div>
          </div>
        </div>
      </div>
    </DashboardLayout>
  )
} 