"use client";

import { UnifiedFileUploader } from "@/components/shared/unified-file-uploader";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { useFormattedDate } from "@/hooks/use-formatted-date";
import {
  Clock,
  Download,
  FileText,
  Paperclip,
  Pencil,
  Plus,
  StickyNote,
  Trash2
} from "lucide-react";
import { useState } from "react";

interface User {
  id: number;
  name: string;
  avatar?: string;
  email?: string;
}

interface TaskFile {
  id: number;
  file_name: string;
  file_url: string;
  file_path: string;
  mime_type: string;
  size: number;
  size_formatted: string;
  created_at: string;
}

interface NoteCreator {
  id: number;
  name: string;
  avatar?: string;
}

interface TaskNote {
  id: number;
  content: string;
  type: "client" | "internal" | "system";
  created_at: string;
  creator?: NoteCreator;
}

interface CommentFile {
  id: number;
  file_name: string;
  file_url: string;
  file_path?: string;
  mime_type?: string;
  size?: number;
  size_formatted?: string;
  project_id?: number;
  phase_id?: number;
  created_at?: string;
}

interface TaskComment {
  id: number;
  content: string;
  created_at: string;
  user: {
    id: number;
    name: string;
    avatar?: string;
  };
  parent_id?: number | null;
  replies?: TaskComment[];
  // Support both 'files' (new API response) and 'attachments' (legacy)
  files?: CommentFile[];
  attachments?: CommentFile[];
}

interface TaskData {
  id: number;
  title: string;
  title_translations?: {
    ar: string;
    en: string;
  };
  description?: string | null;
  description_translations?: {
    ar: string;
    en: string;
  };
  start_date?: string;
  end_date?: string;
  due_date: string;
  assigned_to?: User | null;
  assignees?: User[];
  files?: TaskFile[];
  notes?: TaskNote[];
  comments?: TaskComment[];
  status: string;
  status_label: string;
}

interface ViewTaskDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  task: TaskData;
  locale: "ar" | "en";
  onEdit: () => void;
  onDelete: () => void;
  onUploadAttachment: (file: File) => void;
  onDeleteAttachment: (fileId: number) => void;
  onAddNote: (data: { type: "client" | "internal"; content: string }) => void;
  onEditNote: (
    noteId: number,
    data: { type: "client" | "internal"; content: string },
  ) => void;
  onDeleteNote: (noteId: number) => void;
  translations: {
    title: string;
    nameLabel: string;
    nameEnLabel?: string;
    descriptionLabel?: string;
    descriptionEnLabel?: string;
    assigneeLabel: string;
    assigneesLabel?: string;
    startDateLabel: string;
    endDateLabel?: string;
    dueDateLabel: string;
    statusLabel?: string;
    attachmentsLabel: string;
    uploadNew: string;
    notesLabel: string;
    commentsLabel?: string;
    addNote: string;
    noteTypeLabel: string;
    noteTypePlaceholder: string;
    noteTypeClient: string;
    noteTypeInternal: string;
    noteContentLabel: string;
    noteContentPlaceholder: string;
    saveChanges: string;
    edit: string;
    delete: string;
    by: string;
    cancelButton: string;
    editButton: string;
    deleteButton: string;
  };
}

interface AttachmentItemProps {
  file: TaskFile;
  onDelete: (id: number) => void;
  formatDate: (date: string) => string;
}

function AttachmentItem({ file, onDelete, formatDate }: AttachmentItemProps) {
  return (
    <div className="flex items-center justify-between py-2 px-3 rounded-lg border bg-muted/30">
      <div className="flex items-center gap-2 flex-1 min-w-0">
        <Paperclip className="h-4 w-4 text-muted-foreground shrink-0" />
        <div className="flex-1 min-w-0">
          <a
            href={file.file_url}
            target="_blank"
            rel="noopener noreferrer"
            className="text-sm font-medium truncate hover:underline"
          >
            {file.file_name}
          </a>
          <p className="text-xs text-muted-foreground">
            {file.size_formatted} •{" "}
            {formatDate(file.created_at)}
          </p>
        </div>
      </div>
      <Button
        variant="ghost"
        size="icon"
        className="h-8 w-8 shrink-0"
        onClick={() => onDelete(file.id)}
      >
        <Trash2 className="h-4 w-4 text-destructive" />
      </Button>
    </div>
  );
}

interface NoteItemProps {
  note: TaskNote;
  locale: "ar" | "en";
  onEdit: (id: number) => void;
  onDelete: (id: number) => void;
  isEditing: boolean;
  formatDateTime: (date: string) => string;
  translations: {
    by: string;
    edit: string;
    delete: string;
    noteTypeClient?: string;
    noteTypeInternal?: string;
  };
}

function NoteItem({
  note,
  locale,
  onEdit,
  onDelete,
  isEditing,
  formatDateTime,
  translations,
}: NoteItemProps) {
  void locale;
  const getNoteTypeLabel = () => {
    if (note.type === "client") {
      return translations.noteTypeClient || "ملاحظه العميل";
    }
    return translations.noteTypeInternal || "ملاحظه داخلية";
  };

  return (
    <div className="p-3 border border-border rounded-lg bg-muted/20 dark:bg-card space-y-4">
      {/* Note Header - Note Type (right) | Time (left) in RTL */}
      <div className="flex items-center justify-between">
        {/* Note Type with Icon - appears on RIGHT in RTL */}
        <div className="flex items-center gap-1">
          <StickyNote className="h-4 w-4 text-muted-foreground" />
          <span className="text-xs text-muted-foreground">
            {getNoteTypeLabel()}
          </span>
        </div>
        {/* Time with Clock Icon - appears on LEFT in RTL */}
        <div className="flex items-center gap-1">
          <span className="text-xs text-muted-foreground">
            {formatDateTime(note.created_at)}
          </span>
          <Clock className="h-4 w-4 text-muted-foreground" />
        </div>
      </div>

      {/* Note Content */}
      <p className="text-base text-foreground whitespace-pre-wrap leading-6">
        {note.content}
      </p>

      {/* Note Footer - Creator (right) | Actions (left) in RTL */}
      <div className="flex items-center justify-between">
        {/* Creator Name - appears on RIGHT in RTL */}
        {note.creator && (
          <span className="text-sm text-muted-foreground">
            {translations.by} {note.creator.name}
          </span>
        )}
        {/* Action Buttons - appears on LEFT in RTL */}
        {!isEditing && (
          <div className="flex items-center gap-2">
            <button
              type="button"
              onClick={() => onDelete(note.id)}
              className="h-6 w-6 flex items-center justify-center border border-destructive/30 dark:border-red-800 rounded hover:bg-destructive/10 dark:hover:bg-red-900/20 transition-colors"
            >
              <Trash2 className="h-4 w-4 text-destructive" />
            </button>
            <button
              type="button"
              onClick={() => onEdit(note.id)}
              className="h-6 w-6 flex items-center justify-center border border-border rounded hover:bg-muted transition-colors"
            >
              <Pencil className="h-4 w-4 text-muted-foreground" />
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

interface NoteFormProps {
  initialData?: { type: "client" | "internal"; content: string };
  onSave: (data: { type: "client" | "internal"; content: string }) => void;
  onCancel: () => void;
  translations: {
    noteTypeLabel: string;
    noteTypePlaceholder: string;
    noteTypeClient: string;
    noteTypeInternal: string;
    noteContentLabel: string;
    noteContentPlaceholder: string;
    saveChanges: string;
    cancelButton: string;
  };
}

function NoteForm({
  initialData,
  onSave,
  onCancel,
  translations,
}: NoteFormProps) {
  const [type, setType] = useState<"client" | "internal" | "">(
    initialData?.type || "",
  );
  const [content, setContent] = useState(initialData?.content || "");

  const handleSave = () => {
    if (type && content) {
      onSave({ type: type as "client" | "internal", content });
    }
  };

  return (
    <div className="space-y-4 p-4 rounded-lg border bg-muted/30">
      <div className="space-y-2">
        <Label htmlFor="note-type">{translations.noteTypeLabel}</Label>
        <Select
          value={type}
          onValueChange={(value) => setType(value as "client" | "internal")}
        >
          <SelectTrigger id="note-type">
            <SelectValue placeholder={translations.noteTypePlaceholder} />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="client">
              {translations.noteTypeClient}
            </SelectItem>
            <SelectItem value="internal">
              {translations.noteTypeInternal}
            </SelectItem>
          </SelectContent>
        </Select>
      </div>
      <div className="space-y-2">
        <Label htmlFor="note-content">{translations.noteContentLabel}</Label>
        <Textarea
          id="note-content"
          placeholder={translations.noteContentPlaceholder}
          value={content}
          onChange={(e) => setContent(e.target.value)}
          rows={4}
          className="resize-none"
        />
      </div>
      <div className="flex gap-2 ">
        <Button variant="outline" size="sm" onClick={onCancel}>
          {translations.cancelButton}
        </Button>
        <Button size="sm" onClick={handleSave} disabled={!type || !content}>
          {translations.saveChanges}
        </Button>
      </div>
    </div>
  );
}

export function ViewTaskDialog({
  open,
  onOpenChange,
  task,
  locale,
  onEdit,
  onDelete,
  onUploadAttachment,
  onDeleteAttachment,
  onAddNote,
  onEditNote,
  onDeleteNote,
  translations,
}: ViewTaskDialogProps) {
  const { formatDate, formatDateTime } = useFormattedDate();
  const [isAddingNote, setIsAddingNote] = useState(false);
  const [editingNoteId, setEditingNoteId] = useState<number | null>(null);

  const handleFileUpload = (files: File[]) => {
    const file = files[0];
    if (file) {
      onUploadAttachment(file);
    }
  };

  const handleAddNote = (data: {
    type: "client" | "internal";
    content: string;
  }) => {
    onAddNote(data);
    setIsAddingNote(false);
  };

  const handleEditNote = (data: {
    type: "client" | "internal";
    content: string;
  }) => {
    if (editingNoteId) {
      onEditNote(editingNoteId, data);
      setEditingNoteId(null);
    }
  };

  // Get localized title and description
  const taskTitle = task.title_translations?.[locale] || task.title;
  const taskDescription =
    task.description_translations?.[locale] || task.description || "";

  // Get assignees (support both single assigned_to and multiple assignees)
  const assignees =
    task.assignees && task.assignees.length > 0
      ? task.assignees
      : task.assigned_to
        ? [task.assigned_to]
        : [];

  const editingNote = task.notes?.find((note) => note.id === editingNoteId);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[656px]">
        <DialogHeader className="border-border">
          <DialogTitle>{translations.title}</DialogTitle>
        </DialogHeader>

        <DialogBody className="space-y-6">
          {/* Task Information */}
          <div className="space-y-4">
            {/* Title (AR) */}
            <div className="space-y-2">
              <Label>{translations.nameLabel}</Label>
              <div className="text-sm font-medium text-foreground">
                {taskTitle}
              </div>
            </div>

            {/* Title (EN) if different from current locale */}
            {locale === "ar" && task.title_translations?.en && (
              <div className="space-y-2">
                <Label>{translations.nameEnLabel || "Task Name (EN)"}</Label>
                <div className="text-sm font-medium text-foreground">
                  {task.title_translations.en}
                </div>
              </div>
            )}

            {/* Description */}
            {taskDescription && (
              <div className="space-y-2">
                <Label>{translations.descriptionLabel || "Description"}</Label>
                <div className="text-sm text-muted-foreground whitespace-pre-wrap">
                  {taskDescription}
                </div>
              </div>
            )}

            {/* Description (EN) if different from current locale */}
            {locale === "ar" && task.description_translations?.en && (
              <div className="space-y-2">
                <Label>
                  {translations.descriptionEnLabel || "Description (EN)"}
                </Label>
                <div className="text-sm text-muted-foreground whitespace-pre-wrap">
                  {task.description_translations.en}
                </div>
              </div>
            )}

            {/* Status */}
            {task.status_label && (
              <div className="space-y-2">
                <Label>{translations.statusLabel || "Status"}</Label>
                <div className="text-sm text-foreground">
                  {task.status_label}
                </div>
              </div>
            )}

            {/* Assignees */}
            {assignees.length > 0 && (
              <div className="space-y-2">
                <Label>
                  {assignees.length > 1
                    ? translations.assigneesLabel || "Assignees"
                    : translations.assigneeLabel}
                </Label>
                <div className="flex flex-wrap gap-2">
                  {assignees.map((assignee) => (
                    <div
                      key={assignee.id}
                      className="flex items-center gap-2 py-1 px-2 bg-muted rounded-lg"
                    >
                      <Avatar className="h-6 w-6">
                        <AvatarImage
                          src={assignee.avatar}
                          alt={assignee.name}
                        />
                        <AvatarFallback />
                      </Avatar>
                      <span className="text-sm font-medium">
                        {assignee.name}
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Dates */}
            <div className="grid grid-cols-2 gap-4">
              {task.start_date && (
                <div className="space-y-2">
                  <Label>{translations.startDateLabel}</Label>
                  <div className="text-sm text-muted-foreground">
                    {formatDate(task.start_date)}
                  </div>
                </div>
              )}
              {task.end_date && (
                <div className="space-y-2">
                  <Label>{translations.endDateLabel || "End Date"}</Label>
                  <div className="text-sm text-muted-foreground">
                    {formatDate(task.end_date)}
                  </div>
                </div>
              )}
            </div>
            <div className="space-y-2">
              <Label>{translations.dueDateLabel}</Label>
              <div className="text-sm text-muted-foreground">
                {formatDate(task.due_date)}
              </div>
            </div>
          </div>

          {/* Attachments */}
          {task.files && task.files.length > 0 && (
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <Label className="text-base">
                  {translations.attachmentsLabel}
                </Label>
                <UnifiedFileUploader
                  mode="trigger"
                  onChange={handleFileUpload}
                  multiple={false}
                  useGlobalSettings={false}
                  labels={{ browseText: translations.uploadNew }}
                  triggerContent={
                    <Button variant="outline" size="sm" type="button">
                      <Plus className="h-4 w-4 mr-2" />
                      {translations.uploadNew}
                    </Button>
                  }
                />
              </div>
              <div className="space-y-2">
                {task.files.map((file) => (
                  <AttachmentItem
                    key={file.id}
                    file={file}
                    onDelete={onDeleteAttachment}
                    formatDate={formatDate}
                  />
                ))}
              </div>
            </div>
          )}

          {/* Notes */}
          {task.notes && task.notes.length > 0 && (
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <Label className="text-base">{translations.notesLabel}</Label>
                {!isAddingNote && !editingNoteId && (
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setIsAddingNote(true)}
                  >
                    <Plus className="h-4 w-4 mr-2" />
                    {translations.addNote}
                  </Button>
                )}
              </div>
              <div className="space-y-3">
                {isAddingNote && (
                  <NoteForm
                    onSave={handleAddNote}
                    onCancel={() => setIsAddingNote(false)}
                    translations={translations}
                  />
                )}
                {editingNoteId && editingNote && (
                  <NoteForm
                    initialData={{
                      type:
                        editingNote.type === "system"
                          ? "internal"
                          : editingNote.type,
                      content: editingNote.content,
                    }}
                    onSave={handleEditNote}
                    onCancel={() => setEditingNoteId(null)}
                    translations={translations}
                  />
                )}
                {task.notes.map((note) => (
                  <NoteItem
                    key={note.id}
                    note={note}
                    locale={locale}
                    onEdit={setEditingNoteId}
                    onDelete={onDeleteNote}
                    isEditing={editingNoteId === note.id}
                    formatDateTime={formatDateTime}
                    translations={{
                      by: translations.by,
                      edit: translations.edit,
                      delete: translations.delete,
                      noteTypeClient: translations.noteTypeClient,
                      noteTypeInternal: translations.noteTypeInternal,
                    }}
                  />
                ))}
              </div>
            </div>
          )}

          {/* Comments */}
          {task.comments && task.comments.length > 0 && (
            <div className="space-y-3">
              <Label className="text-base">
                {translations.commentsLabel || "Comments"}
              </Label>
              <div className="space-y-3">
                {task.comments.map((comment) => {
                  // Get files from either 'files' or 'attachments' property
                  const commentFiles = comment.files || comment.attachments || [];

                  // Separate images from other documents
                  const imageFiles = commentFiles.filter(
                    (file) => file.mime_type?.startsWith("image/")
                  );
                  const documentFiles = commentFiles.filter(
                    (file) => !file.mime_type?.startsWith("image/")
                  );

                  return (
                    <div
                      key={comment.id}
                      className="py-3 px-4 rounded-lg border bg-card space-y-2"
                    >
                      <div className="flex items-center gap-2 mb-1">
                        <Avatar className="h-6 w-6">
                          <AvatarImage
                            src={comment.user.avatar}
                            alt={comment.user.name}
                          />
                          <AvatarFallback />
                        </Avatar>
                        <span className="text-xs font-medium">
                          {comment.user.name}
                        </span>
                        <span className="text-xs text-muted-foreground">
                          {formatDateTime(comment.created_at)}
                        </span>
                      </div>
                      <p className="text-sm text-foreground whitespace-pre-wrap">
                        {comment.content}
                      </p>

                      {/* Comment Images Grid */}
                      {imageFiles.length > 0 && (
                        <div className="grid grid-cols-2 sm:grid-cols-3 gap-2 mt-3">
                          {imageFiles.map((file) => (
                            <a
                              key={file.id}
                              href={file.file_url}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="group relative aspect-square rounded-lg overflow-hidden border bg-muted/30 hover:border-primary transition-colors"
                            >
                              <img
                                src={file.file_url}
                                alt={file.file_name}
                                className="w-full h-full object-cover"
                              />
                              <div className="absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors" />
                            </a>
                          ))}
                        </div>
                      )}

                      {/* Comment Documents */}
                      {documentFiles.length > 0 && (
                        <div className="space-y-2 mt-3">
                          {documentFiles.map((file) => (
                            <a
                              key={file.id}
                              href={file.file_url}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="flex items-center gap-3 p-2 rounded-lg border bg-muted/30 hover:bg-muted/50 transition-colors"
                            >
                              <div className="shrink-0 w-8 h-8 rounded bg-primary/10 flex items-center justify-center">
                                <FileText className="h-4 w-4 text-primary" />
                              </div>
                              <div className="flex-1 min-w-0">
                                <p className="text-sm font-medium truncate">
                                  {file.file_name}
                                </p>
                                {file.size_formatted && (
                                  <p className="text-xs text-muted-foreground">
                                    {file.size_formatted}
                                  </p>
                                )}
                              </div>
                              <Download className="h-4 w-4 text-muted-foreground shrink-0" />
                            </a>
                          ))}
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          )}
        </DialogBody>

        <DialogFooter className="flex-row gap-2">
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            {translations.cancelButton}
          </Button>
          <Button variant="destructive" onClick={onDelete}>
            {translations.deleteButton}
          </Button>
          <Button onClick={onEdit}>{translations.editButton}</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
