import { useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useFeesPlans, useStudentFees } from "@/hooks/queries";
import { feesService } from "@/services/fees.service";
import { useToast } from "@/hooks/use-toast";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { useFeesPlan } from "@/hooks/queries";
import { Search, DollarSign, CreditCard, Eye } from "lucide-react";

function planStateBadge(state: string) {
  const s = state?.toLowerCase();
  if (s === "draft") return <Badge variant="secondary">{state}</Badge>;
  if (s === "ongoing") return <Badge variant="default">{state}</Badge>;
  if (s === "done")
    return (
      <Badge variant="outline" className="border-green-600 text-green-700">
        {state}
      </Badge>
    );
  return <Badge variant="outline">{state}</Badge>;
}

export default function AdminFees() {
  const [search, setSearch] = useState("");
  const [section, setSection] = useState<"plans" | "student">("plans");
  const [detailId, setDetailId] = useState<number | null>(null);
  const { toast } = useToast();
  const plansQ = useFeesPlans();
  const feesQ = useStudentFees();
  const detailQ = useFeesPlan(detailId ?? 0);
  const loading = section === "plans" ? plansQ.isLoading : feesQ.isLoading;
  const plans = plansQ.data?.data ?? plansQ.data?.items ?? [];
  const fees = feesQ.data?.data ?? feesQ.data?.items ?? [];

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
      </div>
    );
  }

  const q = search.toLowerCase();
  const filteredPlans = plans.filter(
    (p) =>
      p.student_name?.toLowerCase().includes(q) || p.course_name?.toLowerCase().includes(q),
  );
  const filteredFees = fees.filter((f) => f.student_name?.toLowerCase().includes(q));

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Fees</h1>
        <p className="text-muted-foreground">Fee plans and student fee lines.</p>
      </div>
      <div className="flex flex-wrap gap-2">
        <Button variant={section === "plans" ? "default" : "outline"} onClick={() => setSection("plans")}>
          <DollarSign className="mr-2 h-4 w-4" />
          Fee plans
        </Button>
        <Button variant={section === "student" ? "default" : "outline"} onClick={() => setSection("student")}>
          <CreditCard className="mr-2 h-4 w-4" />
          Student fees
        </Button>
      </div>
      <div className="relative max-w-sm">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
        <Input
          placeholder={section === "plans" ? "Search plans..." : "Search student fees..."}
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="pl-9"
        />
      </div>
      {section === "plans" ? (
        <Card>
          <CardContent className="pt-6">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>#</TableHead>
                  <TableHead>Student</TableHead>
                  <TableHead>Course</TableHead>
                  <TableHead>Total</TableHead>
                  <TableHead>Paid</TableHead>
                  <TableHead>Remaining</TableHead>
                  <TableHead>State</TableHead>
                  <TableHead>Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredPlans.map((p, i) => (
                  <TableRow key={p.id}>
                    <TableCell>{i + 1}</TableCell>
                    <TableCell className="font-medium">{p.student_name}</TableCell>
                    <TableCell>{p.course_name}</TableCell>
                    <TableCell>{p.total_amount}</TableCell>
                    <TableCell>{p.paid_amount}</TableCell>
                    <TableCell>{p.remaining_amount}</TableCell>
                    <TableCell>{planStateBadge(p.state)}</TableCell>
                    <TableCell>
                      <Button size="sm" variant="ghost" onClick={() => setDetailId(p.id)}>
                        <Eye className="h-4 w-4" />
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardContent className="pt-6">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>#</TableHead>
                  <TableHead>Student</TableHead>
                  <TableHead>Amount</TableHead>
                  <TableHead>Date</TableHead>
                  <TableHead>State</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredFees.map((f, i) => (
                  <TableRow key={f.id}>
                    <TableCell>{i + 1}</TableCell>
                    <TableCell className="font-medium">{f.student_name}</TableCell>
                    <TableCell>{f.amount}</TableCell>
                    <TableCell>{f.date}</TableCell>
                    <TableCell>
                      <Badge variant="outline" className="capitalize">
                        {f.state}
                      </Badge>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}
      <Dialog open={!!detailId} onOpenChange={(v) => { if (!v) setDetailId(null); }}>
        <DialogContent>
          <DialogHeader><DialogTitle>Fee Plan Details</DialogTitle></DialogHeader>
          {detailQ.isLoading ? (
            <div className="flex justify-center py-4"><div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary" /></div>
          ) : detailQ.data ? (
            <div className="space-y-2 text-sm">
              <p><span className="font-medium">Student:</span> {detailQ.data.student_name}</p>
              <p><span className="font-medium">Course:</span> {detailQ.data.course_name}</p>
              <p><span className="font-medium">Total:</span> {detailQ.data.total_amount}</p>
              <p><span className="font-medium">Paid:</span> {detailQ.data.paid_amount}</p>
              <p><span className="font-medium">Remaining:</span> {detailQ.data.remaining_amount}</p>
              <p><span className="font-medium">State:</span> {planStateBadge(detailQ.data.state)}</p>
            </div>
          ) : null}
        </DialogContent>
      </Dialog>
    </div>
  );
}
