import { createFileRoute, Link, useParams } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { PageLayout } from "@/components/PageLayout";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { ArrowLeft, Mail, Phone, MapPin, IdCard, Calendar, Briefcase, Building2 } from "lucide-react";
import { format } from "date-fns";

export const Route = createFileRoute("/_authenticated/staff/$staffId")({
  component: StaffProfilePage,
});

function StaffProfilePage() {
  const { staffId } = useParams({ from: "/_authenticated/staff/$staffId" });

  const { data: staff, isLoading } = useQuery({
    queryKey: ["staff", staffId],
    queryFn: async () => {
      const { data, error } = await supabase.from("staff").select("*").eq("id", staffId).single();
      if (error) throw error;
      return data;
    },
  });

  const { data: branch } = useQuery({
    queryKey: ["branch", staff?.branch_id],
    enabled: !!staff?.branch_id,
    queryFn: async () => {
      const { data } = await supabase.from("branches").select("name").eq("id", staff!.branch_id!).maybeSingle();
      return data;
    },
  });

  const { data: department } = useQuery({
    queryKey: ["department", staff?.department_id],
    enabled: !!staff?.department_id,
    queryFn: async () => {
      const { data } = await supabase.from("departments").select("name").eq("id", staff!.department_id!).maybeSingle();
      return data;
    },
  });

  const startOfMonth = format(new Date(new Date().getFullYear(), new Date().getMonth(), 1), "yyyy-MM-dd");
  const { data: attendance = [] } = useQuery({
    queryKey: ["staff-attendance-month", staffId],
    queryFn: async () => {
      const { data } = await supabase
        .from("staff_attendance")
        .select("*")
        .eq("staff_id", staffId)
        .gte("date", startOfMonth)
        .order("date", { ascending: false });
      return data ?? [];
    },
  });

  const { data: payroll = [] } = useQuery({
    queryKey: ["staff-payroll-recent", staffId],
    queryFn: async () => {
      const { data } = await supabase
        .from("staff_payroll")
        .select("*")
        .eq("staff_id", staffId)
        .order("month", { ascending: false })
        .limit(6);
      return data ?? [];
    },
  });

  if (isLoading) return <PageLayout title="Loading..."><div>Loading...</div></PageLayout>;
  if (!staff) return <PageLayout title="Not found"><div>Staff not found</div></PageLayout>;

  const presentCount = attendance.filter((a) => a.status === "present").length;
  const lateCount = attendance.filter((a) => a.status === "late").length;
  const absentCount = attendance.filter((a) => a.status === "absent").length;

  return (
    <PageLayout title="Staff Profile" subtitle={staff.staff_id ?? ""}>
      <div className="mb-4">
        <Link to="/staff">
          <Button variant="outline" size="sm"><ArrowLeft className="h-4 w-4 mr-1" />Back to Staff List</Button>
        </Link>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4 mb-4">
        <Card className="p-6 lg:col-span-1">
          <div className="flex flex-col items-center text-center">
            {staff.photo_url ? (
              <img src={staff.photo_url} alt={staff.name} className="h-28 w-28 rounded-full object-cover mb-3" />
            ) : (
              <div className="h-28 w-28 rounded-full bg-muted flex items-center justify-center text-2xl font-bold mb-3">
                {staff.name.slice(0, 2).toUpperCase()}
              </div>
            )}
            <h2 className="text-xl font-bold">{staff.name}</h2>
            <p className="text-sm text-muted-foreground font-mono">{staff.staff_id}</p>
            <div className="flex gap-2 mt-2">
              <Badge variant="secondary">{staff.role}</Badge>
              <Badge variant={staff.status === "active" ? "default" : "outline"}>{staff.status}</Badge>
            </div>
          </div>
          <div className="border-t mt-4 pt-4 space-y-2 text-sm">
            {staff.mobile && <div className="flex items-center gap-2"><Phone className="h-4 w-4 text-muted-foreground" />{staff.mobile}</div>}
            {staff.email && <div className="flex items-center gap-2"><Mail className="h-4 w-4 text-muted-foreground" />{staff.email}</div>}
            {staff.address && <div className="flex items-start gap-2"><MapPin className="h-4 w-4 text-muted-foreground mt-0.5" />{staff.address}</div>}
            {staff.nid && <div className="flex items-center gap-2"><IdCard className="h-4 w-4 text-muted-foreground" />NID: {staff.nid}</div>}
            {staff.joining_date && <div className="flex items-center gap-2"><Calendar className="h-4 w-4 text-muted-foreground" />Joined: {format(new Date(staff.joining_date), "PP")}</div>}
            {staff.designation && <div className="flex items-center gap-2"><Briefcase className="h-4 w-4 text-muted-foreground" />{staff.designation}</div>}
            {(branch || department) && (
              <div className="flex items-center gap-2"><Building2 className="h-4 w-4 text-muted-foreground" />
                {branch?.name ?? "-"} / {department?.name ?? "-"}
              </div>
            )}
          </div>
        </Card>

        <div className="lg:col-span-2 space-y-4">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
            <Card className="p-4">
              <div className="text-xs text-muted-foreground">Salary</div>
              <div className="text-lg font-bold mt-1">৳{Number(staff.salary).toLocaleString()}</div>
            </Card>
            <Card className="p-4">
              <div className="text-xs text-muted-foreground">Present (this month)</div>
              <div className="text-lg font-bold mt-1 text-green-600">{presentCount}</div>
            </Card>
            <Card className="p-4">
              <div className="text-xs text-muted-foreground">Late</div>
              <div className="text-lg font-bold mt-1 text-amber-600">{lateCount}</div>
            </Card>
            <Card className="p-4">
              <div className="text-xs text-muted-foreground">Absent</div>
              <div className="text-lg font-bold mt-1 text-destructive">{absentCount}</div>
            </Card>
          </div>

          <Card className="p-4">
            <h3 className="font-semibold mb-3">Recent Payroll (last 6 months)</h3>
            {payroll.length === 0 ? (
              <p className="text-sm text-muted-foreground">No payroll records yet.</p>
            ) : (
              <div className="space-y-2">
                {payroll.map((p) => (
                  <div key={p.id} className="flex items-center justify-between p-2 border rounded text-sm">
                    <div>
                      <div className="font-medium">{format(new Date(p.month), "MMMM yyyy")}</div>
                      <div className="text-xs text-muted-foreground">
                        Bonus ৳{p.bonus} · Commission ৳{p.commission} · Deduction ৳{p.deduction}
                      </div>
                    </div>
                    <div className="text-right">
                      <div className="font-bold">৳{Number(p.net_payable).toLocaleString()}</div>
                      <Badge variant={p.status === "paid" ? "default" : "outline"} className="text-xs">{p.status}</Badge>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </Card>

          <Card className="p-4">
            <h3 className="font-semibold mb-3">Recent Attendance</h3>
            {attendance.length === 0 ? (
              <p className="text-sm text-muted-foreground">No attendance records this month.</p>
            ) : (
              <div className="grid grid-cols-2 md:grid-cols-3 gap-2 text-sm">
                {attendance.slice(0, 12).map((a) => (
                  <div key={a.id} className="p-2 border rounded">
                    <div className="text-xs text-muted-foreground">{format(new Date(a.date), "PP")}</div>
                    <Badge variant={a.status === "present" ? "default" : a.status === "absent" ? "destructive" : "secondary"} className="text-xs mt-1">
                      {a.status}
                    </Badge>
                  </div>
                ))}
              </div>
            )}
          </Card>

          {staff.note && (
            <Card className="p-4">
              <h3 className="font-semibold mb-2">Note</h3>
              <p className="text-sm text-muted-foreground whitespace-pre-wrap">{staff.note}</p>
            </Card>
          )}
        </div>
      </div>
    </PageLayout>
  );
}
