import { useState, useEffect, useMemo } from "react";
import {
  Table,
  TableBody,
  TableCell,
  TableHeader,
  TableRow,
} from "../ui/table";

import Badge from "../ui/badge/Badge";
import { LuArrowUpDown, LuArrowUp, LuArrowDown, LuSettings2, LuPlus } from "react-icons/lu";
import Button from "../ui/button/Button";
import { Link } from "react-router";
import { Modal } from "../ui/modal";
import Input from "../form/input/InputField";
import Label from "../form/Label";
import Select from "../form/Select";
import MultiSelect from "../form/MultiSelect";

interface Activity {
  activity_id: number;
  activity_title: string;
  activity_desc: string;
  activity_author: {
    id: number;
    name: string;
  };
  activity_sc_start: string;
  activity_sc_end: string;
  activity_prio: string;
  activity_class: string;
  activity_attachment: string | null;
  activity_team: number[] | null;
  activity_team_details?: { id: number; name: string }[] | null;
  activity_status: string;
}

type SortConfig = {
  key: keyof Activity | "author_name";
  direction: "asc" | "desc" | null;
};

export default function ActivityTable() {
  const [activities, setActivities] = useState<Activity[]>([]);
  const [loading, setLoading] = useState(true);
  const [sortConfig, setSortConfig] = useState<SortConfig>({
    key: "activity_id",
    direction: null,
  });

  const [isAddModalOpen, setIsAddModalOpen] = useState(false);
  const [users, setUsers] = useState<{ user_id: number; user_name: string }[]>([]);
  const [submitting, setSubmitting] = useState(false);
  const [newActivity, setNewActivity] = useState({
    activity_title: "",
    activity_desc: "",
    activity_prio: "low",
    activity_class: "Regular",
    activity_status: "active",
    activity_sc_start: "",
    activity_sc_end: "",
    activity_team: [] as number[],
  });
  const [selectedFile, setSelectedFile] = useState<File | null>(null);

  useEffect(() => {
    fetchActivities();
    fetchUsers();
  }, []);

  const fetchActivities = () => {
    setLoading(true);
    fetch("/api/activities", {
      credentials: "include",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
    })
      .then((res) => res.json())
      .then((data) => {
        setActivities(data);
        setLoading(false);
      })
      .catch((err) => {
        console.error("Failed to fetch activities:", err);
        setLoading(false);
      });
  };

  const fetchUsers = () => {
    fetch("/api/users", {
      credentials: "include",
      headers: { Accept: "application/json" },
    })
      .then(res => res.json())
      .then(data => setUsers(data))
      .catch(err => console.error("Failed to fetch users:", err));
  };

  const handleSort = (key: SortConfig["key"]) => {
    let direction: SortConfig["direction"] = "asc";
    if (sortConfig.key === key && sortConfig.direction === "asc") {
      direction = "desc";
    } else if (sortConfig.key === key && sortConfig.direction === "desc") {
      direction = null;
    }
    setSortConfig({ key, direction });
  };

  const sortedActivities = useMemo(() => {
    if (!sortConfig.direction) return activities;

    const sorted = [...activities].sort((a, b) => {
      let aValue: any;
      let bValue: any;

      if (sortConfig.key === "author_name") {
        aValue = a.activity_author.name.toLowerCase();
        bValue = b.activity_author.name.toLowerCase();
      } else {
        aValue = a[sortConfig.key as keyof Activity];
        bValue = b[sortConfig.key as keyof Activity];
      }

      // Special handling for priority
      if (sortConfig.key === "activity_prio") {
        const priorityOrder: Record<string, number> = {
          urgent: 3,
          moderate: 2,
          low: 1,
        };
        aValue = priorityOrder[aValue as string] || 0;
        bValue = priorityOrder[bValue as string] || 0;
      } else if (
        sortConfig.key === "activity_sc_start" ||
        sortConfig.key === "activity_sc_end"
      ) {
        aValue = new Date(aValue as string).getTime();
        bValue = new Date(bValue as string).getTime();
      }

      if (typeof aValue === "string") {
        aValue = aValue.toLowerCase();
        bValue = bValue.toLowerCase();
      }

      if (aValue < bValue) return sortConfig.direction === "asc" ? -1 : 1;
      if (aValue > bValue) return sortConfig.direction === "asc" ? 1 : -1;
      return 0;
    });

    return sorted;
  }, [activities, sortConfig]);

  const handleAddSubmit = async () => {
    setSubmitting(true);
    try {
      const formData = new FormData();
      formData.append("activity_title", newActivity.activity_title);
      formData.append("activity_desc", newActivity.activity_desc);
      formData.append("activity_prio", newActivity.activity_prio);
      formData.append("activity_class", newActivity.activity_class);
      formData.append("activity_status", newActivity.activity_status);
      formData.append("activity_sc_start", newActivity.activity_sc_start);
      formData.append("activity_sc_end", newActivity.activity_sc_end);
      formData.append("activity_team", newActivity.activity_team.join(", "));
      
      if (selectedFile) {
        formData.append("activity_attachment", selectedFile);
      }

      const response = await fetch("/api/activities", {
        method: "POST",
        credentials: "include",
        headers: {
          Accept: "application/json",
        },
        body: formData,
      });

      if (!response.ok) throw new Error("Failed to add activity");

      setIsAddModalOpen(false);
      setNewActivity({
        activity_title: "",
        activity_desc: "",
        activity_prio: "low",
        activity_class: "Regular",
        activity_status: "active",
        activity_sc_start: "",
        activity_sc_end: "",
        activity_team: [],
      });
      setSelectedFile(null);
      fetchActivities();
    } catch (err: any) {
      alert(err.message);
    } finally {
      setSubmitting(false);
    }
  };

  const getSortIcon = (key: SortConfig["key"]) => {
    if (sortConfig.key !== key || !sortConfig.direction) {
      return <LuArrowUpDown className="ml-1 size-3.5 text-gray-400" />;
    }
    return sortConfig.direction === "asc" ? (
      <LuArrowUp className="ml-1 size-3.5 text-blue-500" />
    ) : (
      <LuArrowDown className="ml-1 size-3.5 text-blue-500" />
    );
  };

  if (loading) {
    return (
      <div className="overflow-hidden rounded-2xl border border-gray-200 bg-white px-4 pb-3 pt-4 dark:border-gray-800 dark:bg-white/[0.03] sm:px-6">
        <div className="flex items-center justify-center p-10">
          <div className="w-8 h-8 border-4 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
        </div>
      </div>
    );
  }

  return (
    <div className="overflow-hidden rounded-2xl border border-gray-200 bg-white px-4 pb-3 pt-4 dark:border-gray-800 dark:bg-white/[0.03] sm:px-6">
      <div className="flex flex-col gap-2 mb-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h3 className="text-lg font-semibold text-gray-800 dark:text-white/90">
            Activity List
          </h3>
        </div>

        <div className="flex items-center gap-3">
          <Button
            variant="outline"
            size="sm"
            startIcon={<LuSettings2 className="size-5" />}
          >
            Filter
          </Button>
          <Button
            variant="outline"
            size="sm"
            startIcon={<LuPlus className="size-5" />}
            onClick={() => setIsAddModalOpen(true)}
          >
            Add Activity
          </Button>
        </div>
      </div>

      <Modal
        isOpen={isAddModalOpen}
        onClose={() => setIsAddModalOpen(false)}
        className="max-w-[700px]"
      >
        <div className="flex flex-col h-full">
          <div className="px-6 py-5 lg:px-10 lg:py-7 border-b border-gray-100 dark:border-gray-800 bg-gray-50/50 dark:bg-white/[0.02]">
            <div className="flex items-center gap-3">
              <div className="flex items-center justify-center size-10 rounded-xl bg-blue-500 text-white shadow-lg shadow-blue-500/20">
                <LuPlus className="size-6" />
              </div>
              <div>
                <h3 className="text-xl font-bold text-gray-800 dark:text-white/90">
                  Add New Activity
                </h3>
                <p className="text-sm text-gray-500 dark:text-gray-400">
                  Fill in the details to create a new activity tracking entry.
                </p>
              </div>
            </div>
          </div>

          <div className="px-6 py-6 lg:px-10 lg:py-8 overflow-y-auto max-h-[70vh] custom-scrollbar">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-5">
              <div className="md:col-span-2">
                <Label>Activity Title</Label>
                <Input
                  placeholder="e.g. Daily Aircraft Maintenance"
                  value={newActivity.activity_title}
                  onChange={(e) => setNewActivity({ ...newActivity, activity_title: e.target.value })}
                  className="mt-1.5"
                />
              </div>

              <div className="md:col-span-2">
                <Label>Description</Label>
                <textarea
                  rows={3}
                  className="w-full mt-1.5 rounded-xl border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 outline-none focus:border-blue-500 dark:border-gray-700 dark:text-white/90 dark:focus:border-blue-500 transition-all focus:ring-4 focus:ring-blue-500/10 shadow-sm"
                  placeholder="Describe the activity..."
                  value={newActivity.activity_desc}
                  onChange={(e) => setNewActivity({ ...newActivity, activity_desc: e.target.value })}
                />
              </div>

              <div>
                <Label>Priority</Label>
                <Select
                  className="mt-1.5"
                  options={[
                    { value: "urgent", label: "Urgent" },
                    { value: "moderate", label: "Moderate" },
                    { value: "low", label: "Low" },
                  ]}
                  value={newActivity.activity_prio}
                  onChange={(val) => setNewActivity({ ...newActivity, activity_prio: val })}
                />
              </div>

              <div>
                <Label>Classification</Label>
                <Select
                  className="mt-1.5"
                  options={[
                    { value: "Regular", label: "Regular" },
                    { value: "Special", label: "Special" },
                    { value: "Emergency", label: "Emergency" },
                  ]}
                  value={newActivity.activity_class}
                  onChange={(val) => setNewActivity({ ...newActivity, activity_class: val })}
                />
              </div>

              <div>
                <Label>Status</Label>
                <Select
                  className="mt-1.5"
                  options={[
                    { value: "active", label: "Active" },
                    { value: "pending", label: "Pending" },
                  ]}
                  value={newActivity.activity_status}
                  onChange={(val) => setNewActivity({ ...newActivity, activity_status: val })}
                />
              </div>

              <div className="md:col-span-1">
                 <Label>Attachment</Label>
                 <div className="mt-1.5">
                   <label className="flex flex-col items-center justify-center w-full h-[110px] border-2 border-dashed border-gray-200 rounded-2xl cursor-pointer hover:border-blue-400 hover:bg-blue-50/30 dark:border-gray-800 dark:hover:border-blue-500/50 dark:hover:bg-blue-500/5 transition-all group relative overflow-hidden">
                     <div className="flex flex-col items-center justify-center px-4 text-center">
                       <div className="size-8 mb-2 flex items-center justify-center rounded-full bg-gray-100 dark:bg-gray-800 group-hover:bg-blue-500 group-hover:text-white transition-colors">
                         <LuPlus className="size-5" />
                       </div>
                       <p className="text-xs font-semibold text-gray-700 dark:text-gray-300">
                         {selectedFile ? selectedFile.name : "Click to upload"}
                       </p>
                       <p className="text-[10px] text-gray-400 mt-1">Max file size 5MB</p>
                     </div>
                     <input 
                      type="file" 
                      className="hidden" 
                      onChange={(e) => setSelectedFile(e.target.files ? e.target.files[0] : null)}
                    />
                   </label>
                 </div>
              </div>

              <div className="md:col-span-2 grid grid-cols-1 md:grid-cols-2 gap-6 pt-2">
                <div>
                  <Label>Schedule Start</Label>
                  <Input
                    type="datetime-local"
                    value={newActivity.activity_sc_start}
                    onChange={(e) => setNewActivity({ ...newActivity, activity_sc_start: e.target.value })}
                    className="mt-1.5"
                  />
                </div>
                <div>
                  <Label>Deadline (End)</Label>
                  <Input
                    type="datetime-local"
                    value={newActivity.activity_sc_end}
                    onChange={(e) => setNewActivity({ ...newActivity, activity_sc_end: e.target.value })}
                    className="mt-1.5"
                  />
                </div>
              </div>

              <div className="md:col-span-2 pt-2">
                <MultiSelect
                  label="Team Assignment"
                  placeholder="Select team members"
                  options={users.map(u => ({ value: String(u.user_id), text: u.user_name }))}
                  value={newActivity.activity_team.map(String)}
                  onChange={(selected) => setNewActivity({ ...newActivity, activity_team: selected.map(Number) })}
                />
              </div>
            </div>
          </div>

          <div className="px-6 py-5 lg:px-10 lg:py-6 flex items-center justify-end gap-3 border-t border-gray-100 dark:border-gray-800 bg-gray-50/50 dark:bg-white/[0.02] rounded-b-3xl">
            <Button
              variant="outline"
              onClick={() => setIsAddModalOpen(false)}
              className="px-6 rounded-xl"
            >
              Cancel
            </Button>
            <Button
              onClick={handleAddSubmit}
              disabled={submitting}
              className="px-8 rounded-xl shadow-lg shadow-blue-500/25"
            >
              {submitting ? "Saving..." : "Create Activity"}
            </Button>
          </div>
        </div>
      </Modal>

      <div className="max-w-full overflow-x-auto">
        <Table>
          <TableHeader className="border-gray-100 dark:border-gray-800 border-y">
            <TableRow>
              <TableCell
                isHeader
                className="py-3 font-medium text-gray-500 text-start text-theme-xs dark:text-gray-400 cursor-pointer hover:bg-gray-50 dark:hover:bg-white/[0.02]"
                onClick={() => handleSort("activity_title")}
              >
                <div className="flex items-center">
                  Activity
                  {getSortIcon("activity_title")}
                </div>
              </TableCell>
              <TableCell
                isHeader
                className="py-3 font-medium text-gray-500 text-start text-theme-xs dark:text-gray-400 cursor-pointer hover:bg-gray-50 dark:hover:bg-white/[0.02]"
                onClick={() => handleSort("activity_sc_start")}
              >
                <div className="flex items-center">
                  Schedule Start
                  {getSortIcon("activity_sc_start")}
                </div>
              </TableCell>
              <TableCell
                isHeader
                className="py-3 font-medium text-gray-500 text-start text-theme-xs dark:text-gray-400 cursor-pointer hover:bg-gray-50 dark:hover:bg-white/[0.02]"
                onClick={() => handleSort("activity_sc_end")}
              >
                <div className="flex items-center">
                  Deadline
                  {getSortIcon("activity_sc_end")}
                </div>
              </TableCell>
              <TableCell
                isHeader
                className="py-3 font-medium text-gray-500 text-start text-theme-xs dark:text-gray-400 cursor-pointer hover:bg-gray-50 dark:hover:bg-white/[0.02]"
                onClick={() => handleSort("activity_prio")}
              >
                <div className="flex items-center">
                  Priority
                  {getSortIcon("activity_prio")}
                </div>
              </TableCell>
              <TableCell
                isHeader
                className="py-3 font-medium text-gray-500 text-start text-theme-xs dark:text-gray-400 cursor-pointer hover:bg-gray-50 dark:hover:bg-white/[0.02]"
                onClick={() => handleSort("activity_class")}
              >
                <div className="flex items-center">
                  Classification
                  {getSortIcon("activity_class")}
                </div>
              </TableCell>
              <TableCell
                isHeader
                className="py-3 font-medium text-gray-500 text-start text-theme-xs dark:text-gray-400 cursor-pointer hover:bg-gray-50 dark:hover:bg-white/[0.02]"
                onClick={() => handleSort("activity_status")}
              >
                <div className="flex items-center">
                  Status
                  {getSortIcon("activity_status")}
                </div>
              </TableCell>
              <TableCell
                isHeader
                className="py-3 font-medium text-gray-500 text-start text-theme-xs dark:text-gray-400"
              >
                Team
              </TableCell>
            </TableRow>
          </TableHeader>

          <TableBody className="divide-y divide-gray-100 dark:divide-gray-800">
            {sortedActivities.length > 0 ? (
              sortedActivities.map((activity: Activity) => (
                <TableRow key={activity.activity_id}>
                  <TableCell className="py-3">
                    <div className="flex items-start gap-3">
                      <div>
                        <Link
                          to={`/activity/${activity.activity_id}`}
                          className="block font-medium text-gray-800 text-theme-sm dark:text-white/90 hover:text-blue-500"
                        >
                          {activity.activity_title}
                        </Link>
                        <span className="block text-gray-500 text-theme-xs dark:text-gray-400">
                          by {activity.activity_author.name}
                        </span>
                      </div>
                      {activity.activity_attachment && (
                        <div className="text-gray-400 mt-1">
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"></path>
                          </svg>
                        </div>
                      )}
                    </div>
                  </TableCell>
                  <TableCell className="py-3 text-gray-500 text-theme-sm dark:text-gray-400">
                    <div className="flex flex-col">
                      <span className="font-medium text-gray-700 dark:text-gray-300">
                        {new Date(activity.activity_sc_start).toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" })}
                      </span>
                      <span className="text-xs text-gray-400">
                        {new Date(activity.activity_sc_start).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}
                      </span>
                    </div>
                  </TableCell>
                  <TableCell className="py-3 text-gray-500 text-theme-sm dark:text-gray-400">
                    <div className="flex flex-col">
                      <span className="font-medium text-gray-700 dark:text-gray-300">
                        {new Date(activity.activity_sc_end).toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" })}
                      </span>
                      <span className="text-xs text-gray-400">
                        {new Date(activity.activity_sc_end).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}
                      </span>
                    </div>
                  </TableCell>
                  <TableCell className="py-3 text-gray-500 text-theme-sm dark:text-gray-400">
                    <Badge size="sm" variant="solid" color={activity.activity_prio === "urgent" ? "error" : activity.activity_prio === "moderate" ? "warning" : "success"}>
                      {activity.activity_prio.charAt(0).toUpperCase() + activity.activity_prio.slice(1)}
                    </Badge>
                  </TableCell>
                  <TableCell className="py-3 text-gray-500 text-theme-sm dark:text-gray-400">
                    <Badge color="info" size="sm">{activity.activity_class}</Badge>
                  </TableCell>
                  <TableCell className="py-3 text-gray-500 text-theme-sm dark:text-gray-400">
                    <Badge size="sm" color={activity.activity_status === "active" ? "success" : "warning"}>
                      {activity.activity_status.charAt(0).toUpperCase() + activity.activity_status.slice(1)}
                    </Badge>
                  </TableCell>
                  <TableCell className="py-3 text-gray-500 text-theme-sm dark:text-gray-400">
                    <div className="flex items-center -space-x-2">
                      {activity.activity_team_details ? (
                        activity.activity_team_details.slice(0, 3).map((member) => (
                          <div key={member.id} title={member.name} className="flex items-center justify-center w-6 h-6 rounded-full border-2 border-white dark:border-gray-900 bg-blue-500 text-[10px] text-white font-bold cursor-help">
                            {member.name.split(' ').map(n => n[0]).join('').substring(0, 2).toUpperCase()}
                          </div>
                        ))
                      ) : (
                        activity.activity_team?.slice(0, 3).map((id: number) => (
                          <div key={id} className="flex items-center justify-center w-6 h-6 rounded-full border-2 border-white dark:border-gray-900 bg-blue-500 text-[10px] text-white font-bold">
                            {id}
                          </div>
                        ))
                      )}
                      {(activity.activity_team?.length ?? 0) > 3 && (
                        <div className="flex items-center justify-center w-6 h-6 rounded-full border-2 border-white dark:border-gray-900 bg-gray-200 text-[10px] text-gray-600 font-bold">
                          +{(activity.activity_team?.length ?? 0) - 3}
                        </div>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell colSpan={7} className="py-10 text-center text-gray-500">No activities found.</TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}
