import { useState, useEffect } from "react";
import { useNavigate, useLocation, useParams } from "react-router-dom";
import { useQueryClient } from "@tanstack/react-query";
import { Button } from "@/shared/common/ui/button";
import {
  Loader2,
  Target,
  Hash,
  Percent,
  ArrowLeft,
  Save,
  Check,
  CalendarDays,
  Grid,
  List,
} from "lucide-react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/common/ui/table";
import { useToast } from "@/shared/common/ui/use-toast";

import { Badge } from "@/shared/common/ui/badge";
import {
  ExtendedEmployeePlanDto,
  useEmployeePlanMutations,
  useSubEmployeePlanByPlanId,
} from "@/performance-management/hooks/useEmployeePlan";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import { useTranslation } from "react-i18next";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/shared/common/ui/card";
import { Tabs, TabsList, TabsTrigger } from "@/shared/common/ui/tabs";
import { Label } from "@/shared/common/ui/label";
import { Input } from "@/shared/common/ui/input";
import { cn } from "@/shared/lib/utils";

// Interface for the data passed via navigation state
interface NavigationStateData {
  parentEmployeePlanId: string;
  employeePositionId: string;
  planId: string;
  serviceId: string;
  planType: "number" | "percent" | string;
  currentQuantity: number;
  expectedQuantity: number;
  month: number;
  timeframe: string;
  planName: string;
  serviceName: string;
  weight: number;
  status: string;
}

// Week data interface
interface WeekData {
  weekNumber: number;
  planned: number;
  employeePlanId: string | null;
}

const WeeklyPlanAssignmentPage = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { t } = useTranslation();
  const { yearId, monthId } = useParams();

  const { toast } = useToast();
  const { handleError } = useErrorHandler(t);
  const [activeTab, setActiveTab] = useState<"table" | "calendar">("table");
  const [isLoadingExistingPlans, setIsLoadingExistingPlans] = useState(false);
  const queryClient = useQueryClient();
  const { create, update } = useEmployeePlanMutations();

  // Get data from navigation state
  const navigationState = location.state as NavigationStateData;

  // Destructure all necessary data from navigation state
  const {
    parentEmployeePlanId,
    employeePositionId,
    planId,
    serviceId,
    planType: initialPlanType,
    expectedQuantity,
    planName,
    serviceName,
    status,
    month: monthFromPlan,
  } = navigationState;

  // Get month from URL param or plan data
  const monthFromUrl = monthId ? parseInt(monthId) : monthFromPlan;

  const [weeks, setWeeks] = useState<WeekData[]>([
    { weekNumber: 1, planned: 0, employeePlanId: null },
    { weekNumber: 2, planned: 0, employeePlanId: null },
    { weekNumber: 3, planned: 0, employeePlanId: null },
    { weekNumber: 4, planned: 0, employeePlanId: null },
  ]);

  const [selectedPlanType, setSelectedPlanType] = useState<
    "number" | "percent"
  >(initialPlanType === "percent" ? "percent" : "number");

  const [isSaving, setIsSaving] = useState(false);

  const { data: existingPlanData, isLoading: isPlanLoading } =
    useSubEmployeePlanByPlanId(navigationState.parentEmployeePlanId);

  // Fetch existing weekly plans for this month.
  // API shape:
  //   { "<monthNumber>": { "week_1": { id, quantity }, "week_2": { id, quantity }, ... } }
  useEffect(() => {
    if (!existingPlanData?.data || !monthFromUrl) return;

    const monthData = existingPlanData.data[monthFromUrl.toString()];
    if (!monthData) return;

    // Build the weeks list dynamically so we render all weeks the API knows
    // about (some months have 5 weeks, others 4).
    const weekEntries = Object.keys(monthData)
      .filter((k) => k.startsWith("week_"))
      .map((k) => {
        const weekNumber = parseInt(k.replace("week_", ""), 10);
        const cell = monthData[k] as
          | { id: string | null; quantity: number }
          | number
          | null
          | undefined;

        // Defensive: handle both the new shape ({ id, quantity }) and any
        // legacy shape that may have returned a bare number.
        if (cell && typeof cell === "object") {
          return {
            weekNumber,
            planned: Number(cell.quantity) || 0,
            employeePlanId: cell.id ?? null,
          };
        }
        return {
          weekNumber,
          planned: typeof cell === "number" ? cell : 0,
          employeePlanId: null,
        };
      })
      .sort((a, b) => a.weekNumber - b.weekNumber);

    if (weekEntries.length > 0) {
      setWeeks(weekEntries);
    }
  }, [existingPlanData, monthFromUrl]);

  // Sync loading state
  useEffect(() => {
    setIsLoadingExistingPlans(isPlanLoading);
  }, [isPlanLoading]);

  // Calculate total planned
  const totalPlanned = weeks.reduce((sum, week) => sum + week.planned, 0);

  // Update a week's value in local state
  const updateWeekValue = (weekNumber: number, value: string) => {
    const newValue = parseInt(value) || 0;
    setWeeks((prevWeeks) =>
      prevWeeks.map((w) =>
        w.weekNumber === weekNumber ? { ...w, planned: newValue } : w,
      ),
    );
  };

  // Quick set helper
  const quickSetForAllWeeks = (value: number) => {
    setWeeks((prevWeeks) => prevWeeks.map((w) => ({ ...w, planned: value })));
  };

  // Save all changes
  const handleSaveAll = async () => {
    if (!planId || !monthFromUrl) return;

    // Check if plan is already accepted
    if (status === "accepted") {
      toast({
        title: t("plans.planAlreadyAccepted", "Plan Already Accepted"),
        description: t(
          "plans.cannotEditAcceptedPlan",
          "This plan has already been accepted and cannot be edited. Please contact your administrator if you need to make changes.",
        ),
        variant: "destructive",
      });
      return;
    }

    setIsSaving(true);
    try {
      // Run sequentially so each create's returned id can be threaded into the
      // next iteration's local state — prevents a duplicate-key error on a
      // second save attempt where the previous create succeeded but the local
      // state still shows employeePlanId = null.
      for (const week of weeks) {
        const employeePlanData: ExtendedEmployeePlanDto = {
          employeePositionId,
          planId,
          serviceId,
          planType: selectedPlanType === "number" ? "number" : selectedPlanType,
          expectedQuantity: week.planned,
          timeframe: "weekly",
          week: week.weekNumber,
          month: monthFromUrl,
          parentEmployeePlanId,
        };

        try {
          if (week.employeePlanId) {
            await update.mutateAsync({
              ...employeePlanData,
              id: week.employeePlanId,
            });
          } else {
            const response = await create.mutateAsync(employeePlanData);
            const newId =
              (response as any)?.data?.id ?? (response as any)?.id;
            if (newId) {
              // Persist the new id so subsequent saves PUT instead of POST.
              setWeeks((prev) =>
                prev.map((w) =>
                  w.weekNumber === week.weekNumber
                    ? { ...w, employeePlanId: newId }
                    : w,
                ),
              );
              week.employeePlanId = newId;
            }
          }
        } catch (err: any) {
          // 400 with duplicate-key constraint → the row already exists in the
          // DB even though our local state didn't have its id. Refetch and
          // bail out of this iteration; the user can re-save and the latest
          // ids will be in state.
          const message: string =
            err?.response?.data?.message ?? err?.message ?? "";
          const isDuplicate =
            err?.response?.status === 400 &&
            (message.toLowerCase().includes("duplicate") ||
              err?.response?.data?.exception?.driverError?.code === "23505");
          if (isDuplicate) {
            await queryClient.invalidateQueries({
              queryKey: ["employee-plans", planId],
            });
            throw new Error(
              "This week already has a saved plan. Refreshing — please try save again.",
            );
          }
          throw err;
        }
      }

      queryClient.invalidateQueries({
        queryKey: ["employee-plans", planId],
      });

      toast({
        title: "Success",
        description: "All weekly targets have been saved successfully.",
      });
    } catch (error) {
      console.error("Failed to save plans:", error);
      handleError(error);
    } finally {
      setIsSaving(false);
    }
  };

  // Get month name
  const getMonthName = (monthNum: number): string => {
    const monthNames = [
      "September",
      "October",
      "November",
      "December",
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
    ];
    return monthNames[monthNum - 1] || `Month ${monthNum}`;
  };

  if (!navigationState) {
    return (
      <div className="p-6">
        <Card className="border-red-200 bg-red-50">
          <CardContent className="pt-6 text-center">
            <h3 className="text-lg font-semibold text-red-700">
              Missing Plan Data
            </h3>
            <p className="text-red-600 mt-2">
              Please go back and select a plan to continue.
            </p>
            <Button
              onClick={() =>
                navigate(`/performance-management/${yearId}/employee-plans`)
              }
              className="mt-4"
            >
              <ArrowLeft className="h-4 w-4 mr-2" /> Back to Plans
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="p-6">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-4">
          <Button
            variant="outline"
            size="sm"
            onClick={() =>
              navigate(`/performance-management/${yearId}/employee-plans`)
            }
          >
            <ArrowLeft className="h-4 w-4 mr-2" /> Back to Plans
          </Button>
          <div>
            <h1 className="text-2xl font-bold text-gray-900">
              Weekly Plan Assignment - {planName}
            </h1>
            <p className="text-gray-600 mt-1">
              Set weekly targets for {getMonthName(monthFromUrl)} (4 weeks)
            </p>
          </div>
        </div>
        <div className="flex items-center gap-3">
          <Button
            onClick={handleSaveAll}
            disabled={
              isSaving ||
              create.isPending ||
              update.isPending ||
              status === "accepted"
            }
            className="bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-700 hover:to-indigo-700 text-white shadow-lg"
          >
            {isSaving ? (
              <>
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                Saving...
              </>
            ) : (
              <>
                <Save className="h-4 w-4 mr-2" />
                Save Changes
              </>
            )}
          </Button>
        </div>
      </div>

      {/* Alert for Accepted Plans */}
      {status === "accepted" && (
        <Card className="mb-6 border-red-200 bg-red-50">
          <CardContent className="pt-6">
            <div className="flex items-start gap-4">
              <div className="text-red-600 mt-0.5">
                <svg
                  className="h-5 w-5"
                  fill="currentColor"
                  viewBox="0 0 20 20"
                >
                  <path
                    fillRule="evenodd"
                    d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
                    clipRule="evenodd"
                  />
                </svg>
              </div>
              <div className="flex-1">
                <h3 className="font-semibold text-red-900">
                  {t("plans.planAlreadyAccepted", "Plan Already Accepted")}
                </h3>
                <p className="text-red-700 text-sm mt-1">
                  {t(
                    "plans.cannotEditAcceptedPlan",
                    "This plan has already been accepted and cannot be edited. Please contact your administrator if you need to make changes.",
                  )}
                </p>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Summary Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
        {[
          {
            title: "Service",
            value: serviceName,
            icon: Target,
            color: "blue",
          },
          {
            title: "Monthly Target",
            value: expectedQuantity,
            icon: selectedPlanType === "number" ? Hash : Percent,
            color: "green",
            subtitle: selectedPlanType === "number" ? "Number" : "Number",
          },
          {
            title: "Current Total",
            value: totalPlanned,
            icon: Target,
            color: "purple",
          },
          {
            title: "Month",
            value: getMonthName(monthFromUrl),
            icon: CalendarDays,
            color: "red",
            subtitle: `${weeks.length} weeks`,
          },
        ].map((card, idx) => (
          <Card key={idx}>
            <CardContent className="pt-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">
                    {card.title}
                  </p>
                  <p className="text-2xl font-bold">{card.value}</p>
                  {card.subtitle && (
                    <p className="text-xs text-gray-500 mt-1">
                      {card.subtitle}
                    </p>
                  )}
                </div>
                <div className={`p-2 bg-${card.color}-100 rounded-lg`}>
                  <card.icon className={`h-6 w-6 text-${card.color}-600`} />
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* View Toggle */}
      <Card className="mb-6">
        <CardContent className="pt-6">
          <div className="flex flex-col space-y-4">
            <Tabs
              value={activeTab}
              onValueChange={(v: string) =>
                setActiveTab(v as "table" | "calendar")
              }
            >
              <TabsList className="grid w-full max-w-md grid-cols-2">
                <TabsTrigger value="table" className="flex items-center gap-2">
                  <List className="h-4 w-4" /> Table View
                </TabsTrigger>
                <TabsTrigger
                  value="calendar"
                  className="flex items-center gap-2"
                >
                  <Grid className="h-4 w-4" /> Calendar View
                </TabsTrigger>
              </TabsList>
            </Tabs>

            {/* Plan Type Selection */}
            <div className="flex items-center gap-4">
              <div>
                <Label>Plan Type</Label>
                <div className="flex gap-2 mt-1">
                  <Button
                    variant={
                      selectedPlanType === "number" ? "default" : "outline"
                    }
                    size="sm"
                    onClick={() => setSelectedPlanType("number")}
                    className="gap-2"
                  >
                    <Hash className="h-4 w-4" /> Number
                  </Button>
                  <Button
                    variant={
                      selectedPlanType === "number" ? "default" : "outline"
                    }
                    size="sm"
                    onClick={() => setSelectedPlanType("number")}
                    className="gap-2"
                  >
                    <Percent className="h-4 w-4" /> Percent
                  </Button>
                </div>
              </div>
              <div className="ml-auto">
                <div className="flex gap-2 items-center">
                  <p className="text-sm text-gray-500 mr-2">Quick Set:</p>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => quickSetForAllWeeks(10)}
                  >
                    10
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => quickSetForAllWeeks(25)}
                  >
                    25
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => quickSetForAllWeeks(50)}
                  >
                    50
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => quickSetForAllWeeks(0)}
                  >
                    Clear
                  </Button>
                </div>
              </div>
            </div>

            {/* Month Info */}
            <div className="mt-4 p-4 bg-gray-50 rounded-lg">
              <div className="flex items-center justify-between">
                <div>
                  <h4 className="font-semibold text-gray-900">
                    {getMonthName(monthFromUrl)} Weekly Planning
                  </h4>
                  <p className="text-sm text-gray-600">
                    Set weekly targets below. Don't forget to save your changes.
                  </p>
                </div>
                <Badge
                  variant={status === "accepted" ? "default" : "secondary"}
                >
                  Status: {status}
                </Badge>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Loading State */}
      {isLoadingExistingPlans ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="h-8 w-8 animate-spin text-purple-600" />
          <span className="ml-2 text-gray-600">
            Loading existing weekly plans...
          </span>
        </div>
      ) : activeTab === "table" ? (
        <Card className="overflow-hidden">
          <CardHeader>
            <div className="flex justify-between items-center">
              <div>
                <CardTitle>
                  Weekly Targets for {getMonthName(monthFromUrl)}
                </CardTitle>
                <CardDescription>
                  Enter targets for each week directly in the input fields.
                </CardDescription>
              </div>
              <div className="flex items-center gap-2">
                <Badge variant="outline" className="font-medium">
                  {selectedPlanType === "number" ? "Units" : "Percent"}
                </Badge>
                <Badge className="bg-blue-100 text-blue-800 border-blue-200">
                  Total Planned: {totalPlanned}
                </Badge>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[250px]">Week</TableHead>
                  <TableHead className="text-center">Week 1</TableHead>
                  <TableHead className="text-center">Week 2</TableHead>
                  <TableHead className="text-center">Week 3</TableHead>
                  <TableHead className="text-center">Week 4</TableHead>
                  <TableHead className="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                <TableRow className="hover:bg-gray-50">
                  <TableCell>
                    <div className="flex items-center gap-3">
                      <div className="w-8 h-8 bg-purple-100 rounded-full flex items-center justify-center">
                        <span className="text-purple-600 font-medium">M</span>
                      </div>
                      <div>
                        <p className="font-medium text-gray-900">
                          My Weekly Targets
                        </p>
                        <p className="text-sm text-gray-500">
                          Month {monthFromUrl}
                        </p>
                      </div>
                    </div>
                  </TableCell>

                  {/* Weekly Cells */}
                  {weeks.map((week) => (
                    <TableCell
                      key={week.weekNumber}
                      className="text-center p-2"
                    >
                      <Input
                        type="number"
                        min="0"
                        value={week.planned || ""}
                        onChange={(e) =>
                          updateWeekValue(week.weekNumber, e.target.value)
                        }
                        className={cn(
                          "h-10 w-24 text-center mx-auto transition-all",
                          week.planned > 0
                            ? "border-purple-300 bg-purple-50 font-semibold text-purple-900"
                            : "border-gray-200 text-gray-500",
                        )}
                      />
                    </TableCell>
                  ))}

                  <TableCell className="text-right">
                    <div className="flex items-center justify-end gap-2 text-sm text-gray-500">
                      {totalPlanned > 0 ? (
                        <Check className="h-4 w-4 text-green-500" />
                      ) : (
                        <div className="h-4 w-4" />
                      )}
                      <span>Total: {totalPlanned}</span>
                    </div>
                  </TableCell>
                </TableRow>
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardHeader>
            <CardTitle>Calendar View</CardTitle>
            <CardDescription>
              Coming soon: Interactive calendar view for weekly planning
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="text-center py-12">
              <CalendarDays className="h-12 w-12 mx-auto text-gray-400 mb-4" />
              <h3 className="text-lg font-semibold text-gray-900">
                Calendar View in Development
              </h3>
              <p className="text-gray-600 mt-2">
                This feature will be available in the next update.
              </p>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
};

export default WeeklyPlanAssignmentPage;
