"use client";

import { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import {
  ArrowLeft,
  ClipboardList,
  Info,
  FileText,
  X,
  CheckCircle2,
  AlertCircle,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { Badge } from "@/components/ui/badge";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  useGetTask,
  useUpdateTask,
  useGetServiceDetail,
} from "../hook/task.hook";
import { TaskDocument } from "../type/task.type";

const STATUS_OPTIONS = ["PENDING", "IN_PROGRESS", "COMPLETED"];
const STATUS_LABELS: Record<string, string> = {
  PENDING: "Pending",
  IN_PROGRESS: "In Progress",
  COMPLETED: "Completed",
};
const STATUS_STYLES: Record<string, string> = {
  PENDING: "bg-yellow-500/15 text-yellow-700 border-yellow-200",
  IN_PROGRESS: "bg-blue-500/15 text-blue-700 border-blue-200",
  COMPLETED: "bg-green-500/15 text-green-700 border-green-200",
};

const formatSize = (kb?: number) =>
  !kb ? "" : kb < 1024 ? `${kb} KB` : `${(kb / 1024).toFixed(1)} MB`;

export function EditTaskPage({ taskId }: { taskId: string }) {
  const router = useRouter();
  const { data, isLoading } = useGetTask(taskId);
  const task = data?.data;

  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [dueDate, setDueDate] = useState("");
  const [status, setStatus] = useState("");
  const [error, setError] = useState("");

  const [reqFiles, setReqFiles] = useState<Record<string, File>>({});
  const [removeReqDocIds, setRemoveReqDocIds] = useState<string[]>([]);
  const [otherFiles, setOtherFiles] = useState<File[]>([]);
  const [removeOtherDocIds, setRemoveOtherDocIds] = useState<string[]>([]);

  const { data: serviceDetailRes, isLoading: loadingDetail } =
    useGetServiceDetail(task?.service?.id ?? "");
  const updateTask = useUpdateTask(taskId, () =>
    router.push(`/client/tasks/${taskId}`)
  );

  useEffect(() => {
    if (task) {
      setTitle(task.title ?? "");
      setDescription(task.description ?? "");
      setDueDate(task.dueDate ? task.dueDate.slice(0, 10) : "");
      setStatus(task.status ?? "");
    }
  }, [task]);

  const requirements = serviceDetailRes?.data.serviceDocuments ?? [];
  const allDocs: TaskDocument[] = task?.documents ?? [];

  const existingReqDocMap = useMemo(() => {
    const map: Record<string, TaskDocument> = {};
    allDocs.forEach((doc) => {
      if (doc.serviceDocument?.id) map[doc.serviceDocument.id] = doc;
    });
    return map;
  }, [allDocs]);

  const otherExistingDocs = useMemo(
    () => allDocs.filter((doc) => !doc.serviceDocument?.id),
    [allDocs]
  );

  const missingRequired = requirements.filter((r) => {
    if (!r.isRequired) return false;
    const existing = existingReqDocMap[r.id];
    if (existing && !removeReqDocIds.includes(existing.id)) return false;
    if (reqFiles[r.id]) return false;
    return true;
  });

  const handleReqFile = (serviceDocumentId: string, file: File | null) => {
    setReqFiles((prev) => {
      const next = { ...prev };
      if (file) next[serviceDocumentId] = file;
      else delete next[serviceDocumentId];
      return next;
    });
  };

  const handleSubmit = () => {
    if (!title.trim()) {
      setError("Task title is required");
      return;
    }
    setError("");
    const formData = new FormData();
    formData.append("title", title.trim());
    if (description.trim()) formData.append("description", description.trim());
    if (dueDate) formData.append("dueDate", dueDate);
    if (status) formData.append("status", status);
    const allRemoveIds = [...removeReqDocIds, ...removeOtherDocIds];
    if (allRemoveIds.length)
      formData.append("removeDocumentIds", JSON.stringify(allRemoveIds));
    Object.entries(reqFiles).forEach(([id, file]) => formData.append(id, file));
    otherFiles.forEach((file) => formData.append("other", file));
    updateTask.mutate(formData);
  };

  const initials = title.trim().slice(0, 2).toUpperCase();

  if (isLoading) {
    return (
      <div className="space-y-4">
        <Skeleton className="h-8 w-24" />
        <div className="flex flex-col md:flex-row gap-5">
          <Skeleton className="h-48 md:w-56 w-full rounded-xl" />
          <Skeleton className="h-64 w-full rounded-xl" />
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <button
        onClick={() => router.back()}
        className="text-muted-foreground hover:text-foreground flex items-center gap-1 text-sm"
      >
        <ArrowLeft className="h-4 w-4" /> Back
      </button>
      <div>
        <h2 className="text-2xl font-bold tracking-tight">Edit Task</h2>
        <p className="text-muted-foreground text-sm mt-0.5">
          Update task details and manage documents
        </p>
      </div>

      <div className="flex flex-col md:flex-row gap-5 items-start w-full">
        {/* RIGHT */}
        <Card className="w-full">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              {/* <ClipboardList className="h-4 w-4 text-primary" />
              Task Details */}
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* Title */}
            <div className="space-y-1.5">
              <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                Title <span className="text-destructive">*</span>
              </Label>
              <Input
                value={title}
                readOnly
                onChange={(e) => {
                  setTitle(e.target.value);
                  setError("");
                }}
                placeholder="e.g. GST Filing - July 2026"
                className={error ? "border-destructive" : ""}
              />
              {error && <p className="text-xs text-destructive">{error}</p>}
            </div>

            {/* Description */}
            <div className="space-y-1.5">
              <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                Note
              </Label>
              <Textarea
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                placeholder="Add more details about this task"
                rows={3}
                className="resize-none text-sm"
              />
            </div>

            {/* Due Date + Status */}
              <div className="space-y-1.5">
                <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                  Due Date
                </Label>
                <Input
                  type="date"
                  value={dueDate}
                  onChange={(e) => setDueDate(e.target.value)}
                />
              </div>
              {/* <div className="space-y-1.5">
                <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                  Status
                </Label>
                <Select value={status} onValueChange={setStatus}>
                  <SelectTrigger className="h-9 text-sm w-full">
                    <SelectValue placeholder="Select status" />
                  </SelectTrigger>
                  <SelectContent>
                    {STATUS_OPTIONS.map((s) => (
                      <SelectItem key={s} value={s}>
                        <Badge
                          variant="outline"
                          className={`text-[10px] border ${
                            STATUS_STYLES[s] ?? ""
                          }`}
                        >
                          {STATUS_LABELS[s]}
                        </Badge>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div> */}
       

            {/* Documents */}
            <div className="pt-4 border-t border-border space-y-3">
              <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide flex items-center gap-1.5">
                <FileText className="h-3.5 w-3.5" /> Documents
              </p>

              {loadingDetail ? (
                <p className="text-sm text-muted-foreground">
                  Loading document requirements...
                </p>
              ) : requirements.length === 0 ? (
                <p className="text-sm text-muted-foreground">
                  No specific documents required for this service.
                </p>
              ) : (
                <div className="space-y-2">
                  <p className="text-xs text-muted-foreground font-medium uppercase tracking-wide">
                    Service Documents
                  </p>
                  {requirements.map((req) => {
                    const existingDoc = existingReqDocMap[req.id];
                    const isRemoved =
                      !!existingDoc && removeReqDocIds.includes(existingDoc.id);
                    const newFile = reqFiles[req.id];
                    const isUploaded =
                      (!isRemoved && !!existingDoc) || !!newFile;

                    return (
                      <div
                        key={req.id}
                        className={`flex items-center justify-between rounded-lg border px-3 py-2.5 transition-colors ${
                          isUploaded
                            ? "border-green-200 bg-green-500/5"
                            : "border-border"
                        }`}
                      >
                        <div className="flex items-center gap-2.5 min-w-0">
                          {isUploaded ? (
                            <CheckCircle2 className="w-4 h-4 text-green-600 shrink-0" />
                          ) : (
                            <FileText className="w-4 h-4 text-muted-foreground shrink-0" />
                          )}
                          <div className="min-w-0">
                            <p className="text-sm font-medium truncate">
                              {req.name}
                            </p>
                            {newFile && (
                              <p className="text-xs text-green-600 truncate">
                                {newFile.name} · New
                              </p>
                            )}
                            {!newFile && existingDoc && !isRemoved && (
                              <p className="text-xs text-muted-foreground truncate">
                                {existingDoc.fileName}
                                {existingDoc.fileSizeKb
                                  ? ` · ${formatSize(existingDoc.fileSizeKb)}`
                                  : ""}
                              </p>
                            )}
                            {isRemoved && (
                              <p className="text-xs text-red-500 truncate">
                                Removed
                              </p>
                            )}
                          </div>
                          <Badge
                            variant={req.isRequired ? "default" : "secondary"}
                            className="text-[10px] shrink-0"
                          >
                            {req.isRequired ? "Required" : "Optional"}
                          </Badge>
                        </div>

                        <div className="flex items-center gap-1.5 shrink-0 ml-2">
                          {newFile ? (
                            <button
                              type="button"
                              onClick={() => handleReqFile(req.id, null)}
                              className="text-muted-foreground hover:text-destructive transition-colors"
                            >
                              <X className="w-4 h-4" />
                            </button>
                          ) : existingDoc && !isRemoved ? (
                            <div className="flex items-center gap-1.5">
                              <label className="text-xs text-primary font-medium cursor-pointer hover:underline">
                                Replace
                                <input
                                  type="file"
                                  hidden
                                  onChange={(e) => {
                                    setRemoveReqDocIds((prev) => [
                                      ...prev,
                                      existingDoc.id,
                                    ]);
                                    handleReqFile(
                                      req.id,
                                      e.target.files?.[0] ?? null
                                    );
                                  }}
                                />
                              </label>
                              <button
                                type="button"
                                onClick={() =>
                                  setRemoveReqDocIds((prev) => [
                                    ...prev,
                                    existingDoc.id,
                                  ])
                                }
                                className="text-muted-foreground hover:text-destructive transition-colors"
                              >
                                <X className="w-4 h-4" />
                              </button>
                            </div>
                          ) : isRemoved ? (
                            <div className="flex items-center gap-1.5">
                              <button
                                type="button"
                                onClick={() =>
                                  setRemoveReqDocIds((prev) =>
                                    prev.filter((id) => id !== existingDoc!.id)
                                  )
                                }
                                className="text-xs text-primary hover:underline"
                              >
                                Undo
                              </button>
                              <label className="text-xs text-muted-foreground font-medium cursor-pointer hover:underline">
                                Upload new
                                <input
                                  type="file"
                                  hidden
                                  onChange={(e) =>
                                    handleReqFile(
                                      req.id,
                                      e.target.files?.[0] ?? null
                                    )
                                  }
                                />
                              </label>
                            </div>
                          ) : (
                            <label className="text-xs text-primary font-medium cursor-pointer hover:underline">
                              Upload
                              <input
                                type="file"
                                hidden
                                onChange={(e) =>
                                  handleReqFile(
                                    req.id,
                                    e.target.files?.[0] ?? null
                                  )
                                }
                              />
                            </label>
                          )}
                        </div>
                      </div>
                    );
                  })}

                  {missingRequired.length > 0 && (
                    <div className="flex items-center gap-1.5 text-xs text-amber-600 bg-amber-500/10 rounded-md px-3 py-2">
                      <AlertCircle className="w-3.5 h-3.5 shrink-0" />
                      Missing: {missingRequired.map((d) => d.name).join(", ")}
                    </div>
                  )}
                </div>
              )}

              {/* Other Documents */}
              {/* <div className="space-y-2">
                <p className="text-xs text-muted-foreground font-medium uppercase tracking-wide">Other Documents</p>

                {otherExistingDocs.length > 0 && (
                  <div className="rounded-lg border divide-y overflow-hidden">
                    {otherExistingDocs.map((doc) => {
                      const isRemoved = removeOtherDocIds.includes(doc.id);
                      return (
                        <div key={doc.id}
                          className={`flex items-center justify-between gap-3 px-3 py-2.5 transition-colors ${
                            isRemoved ? "bg-red-50 opacity-60" : "bg-background hover:bg-muted/30"
                          }`}
                        >
                          <div className="flex items-center gap-2.5 min-w-0">
                            <FileText className="w-4 h-4 text-muted-foreground shrink-0" />
                            <div className="min-w-0">
                              <p className={`text-sm font-medium truncate ${isRemoved ? "line-through text-muted-foreground" : ""}`}>
                                {doc.fileName}
                              </p>
                              <p className="text-[11px] text-muted-foreground">
                                {formatSize(doc.fileSizeKb)}
                                {isRemoved && <span className="ml-1 text-red-500 font-medium">· Will be removed</span>}
                              </p>
                            </div>
                          </div>
                          {isRemoved ? (
                            <button type="button"
                              onClick={() => setRemoveOtherDocIds((prev) => prev.filter((id) => id !== doc.id))}
                              className="text-xs text-primary hover:underline shrink-0">
                              Undo
                            </button>
                          ) : (
                            <button type="button"
                              onClick={() => setRemoveOtherDocIds((prev) => [...prev, doc.id])}
                              className="text-muted-foreground hover:text-destructive transition-colors shrink-0">
                              <X className="h-4 w-4" />
                            </button>
                          )}
                        </div>
                      );
                    })}
                  </div>
                )}

                {otherFiles.length > 0 && (
                  <div className="rounded-lg border divide-y overflow-hidden">
                    {otherFiles.map((file, idx) => (
                      <div key={idx} className="flex items-center justify-between gap-2 px-3 py-2 bg-green-50">
                        <div className="flex items-center gap-2 min-w-0">
                          <CheckCircle2 className="h-4 w-4 text-green-600 shrink-0" />
                          <div className="min-w-0">
                            <p className="text-sm font-medium truncate">{file.name}</p>
                            <p className="text-[11px] text-muted-foreground">
                              {(file.size / 1024).toFixed(0)} KB · <span className="text-green-600 font-medium">New</span>
                            </p>
                          </div>
                        </div>
                        <button type="button" onClick={() => setOtherFiles((prev) => prev.filter((_, i) => i !== idx))}
                          className="text-muted-foreground hover:text-destructive transition-colors shrink-0">
                          <X className="h-4 w-4" />
                        </button>
                      </div>
                    ))}
                  </div>
                )}

                <label className="flex items-center gap-3 border-2 border-dashed rounded-lg px-4 py-3 cursor-pointer hover:bg-muted/40 transition-colors">
                  <FileText className="w-5 h-5 text-muted-foreground/60 shrink-0" />
                  <div>
                    <p className="text-sm text-muted-foreground">Click to add extra files</p>
                    <p className="text-xs text-muted-foreground/60">Any file type accepted</p>
                  </div>
                  <input type="file" multiple hidden
                    onChange={(e) => { if (e.target.files) setOtherFiles((prev) => [...prev, ...Array.from(e.target.files!)]); }} />
                </label>
              </div> */}
            </div>

            <div className="flex items-center justify-end gap-3 mt-4 pt-4 border-t border-border">
              <Button
                variant="ghost"
                className="border border-border"
                onClick={() => router.push(`/client/tasks/${taskId}`)}
              >
                Cancel
              </Button>
              <Button onClick={handleSubmit} disabled={updateTask.isPending}>
                {updateTask.isPending && (
                  <div className="w-4 h-4 border-2 border-primary-foreground border-t-transparent rounded-full animate-spin mr-2" />
                )}
                Save Changes
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
