import { useEffect, useMemo, useState, type FormEvent } from "react";
import { ArrowLeft, Download, FileText, Image as ImageIcon, Upload } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { getStoredToken } from "@/lib/auth";
import {
  attachmentDownloadURL,
  getCalendarItem,
  listAttachments,
  uploadAttachment,
  type Attachment,
  type CalendarItem,
} from "@/lib/calendar";

type PostDetailViewProps = {
  itemId: string;
  onBack: () => void;
};

const statusLabels: Record<CalendarItem["status"], string> = {
  rascunho: "Rascunho",
  planejado: "Planejado",
  em_producao: "Em produção",
  em_revisao: "Em revisão",
  aprovado: "Aprovado",
  publicado: "Publicado",
  cancelado: "Cancelado",
};

const dateFormatter = new Intl.DateTimeFormat("pt-BR", { day: "2-digit", month: "long", year: "numeric" });

export function PostDetailView({ itemId, onBack }: PostDetailViewProps) {
  const [item, setItem] = useState<CalendarItem | null>(null);
  const [attachments, setAttachments] = useState<Attachment[]>([]);
  const [previewAttachment, setPreviewAttachment] = useState<Attachment | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const [error, setError] = useState("");
  const [attachmentError, setAttachmentError] = useState("");

  const imageAttachments = useMemo(() => attachments.filter((attachment) => isImageAttachment(attachment)), [attachments]);
  const fileAttachments = useMemo(() => attachments.filter((attachment) => !isImageAttachment(attachment)), [attachments]);

  useEffect(() => {
    const token = getStoredToken();
    if (!token) return;

    setIsLoading(true);
    setError("");
    Promise.all([getCalendarItem(token, itemId), listAttachments(token, itemId)])
      .then(([loadedItem, loadedAttachments]) => {
        setItem(loadedItem);
        setAttachments(loadedAttachments);
      })
      .catch((err) => {
        setError(err instanceof Error ? err.message : "Não foi possível carregar a postagem.");
      })
      .finally(() => setIsLoading(false));
  }, [itemId]);

  async function handleUploadAttachment(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const token = getStoredToken();
    const fileInput = event.currentTarget.elements.namedItem("attachment") as HTMLInputElement | null;
    const file = fileInput?.files?.[0];
    if (!token || !file) return;

    setIsUploading(true);
    setAttachmentError("");
    try {
      const attachment = await uploadAttachment(token, itemId, file);
      setAttachments((current) => [attachment, ...current]);
      if (fileInput) fileInput.value = "";
    } catch (err) {
      setAttachmentError(err instanceof Error ? err.message : "Não foi possível enviar o anexo.");
    } finally {
      setIsUploading(false);
    }
  }

  if (isLoading && !item) {
    return <p className="text-sm text-muted-foreground">Carregando postagem...</p>;
  }

  if (error) {
    return (
      <div className="space-y-4">
        <Button variant="outline" size="sm" onClick={onBack}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          Voltar
        </Button>
        <div className="rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">
          {error}
        </div>
      </div>
    );
  }

  if (!item) return null;

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
        <div className="space-y-3">
          <Button variant="outline" size="sm" onClick={onBack}>
            <ArrowLeft className="mr-2 h-4 w-4" />
            Voltar
          </Button>
          <div>
            <div className="flex flex-wrap items-center gap-2">
              <h1 className="text-2xl font-semibold tracking-tight">{item.title}</h1>
              <Badge variant="secondary" className="bg-orange-500/10 text-orange-700 dark:text-orange-300">
                {statusLabels[item.status]}
              </Badge>
            </div>
            <p className="text-sm text-muted-foreground mt-1">
              {item.client_name} · {dateFormatter.format(parseDateValue(item.scheduled_date))}
            </p>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
        <div className="space-y-6 lg:col-span-2">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Detalhes</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <ReadOnlyField label="Resumo" value={item.description} fallback="Sem resumo." />
              <ReadOnlyField label="Texto da postagem" value={item.copy_text} fallback="Sem texto cadastrado." multiline />
              <ReadOnlyField label="Notas para o cliente" value={item.client_notes} fallback="Sem notas para o cliente." multiline />
              <ReadOnlyField label="Notas internas" value={item.internal_notes} fallback="Sem notas internas." multiline />
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle className="text-base">Anexos</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <form className="grid gap-3 sm:grid-cols-[1fr_auto]" onSubmit={handleUploadAttachment}>
                <div className="grid gap-2">
                  <Label htmlFor="post-detail-attachment">Enviar anexo</Label>
                  <Input id="post-detail-attachment" name="attachment" type="file" accept="image/jpeg,image/png,image/webp,application/pdf" />
                </div>
                <Button className="sm:self-end" type="submit" disabled={isUploading}>
                  <Upload className="mr-2 h-4 w-4" />
                  {isUploading ? "Enviando..." : "Enviar"}
                </Button>
              </form>

              {attachmentError && (
                <div className="rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">
                  {attachmentError}
                </div>
              )}

              {attachments.length === 0 && (
                <p className="text-sm text-muted-foreground py-4">Nenhum anexo enviado.</p>
              )}

              {imageAttachments.length > 0 && (
                <div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
                  {imageAttachments.map((attachment) => (
                    <button
                      key={attachment.id}
                      type="button"
                      className="group overflow-hidden rounded-lg border border-border/60 bg-muted/20 text-left"
                      onClick={() => setPreviewAttachment(attachment)}
                    >
                      <img
                        src={attachmentDownloadURL(attachment.id)}
                        alt={attachment.original_filename}
                        className="aspect-square w-full object-cover transition group-hover:scale-[1.02]"
                      />
                      <div className="flex items-center gap-2 px-2 py-2 text-xs">
                        <ImageIcon className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                        <span className="truncate">{attachment.original_filename}</span>
                      </div>
                    </button>
                  ))}
                </div>
              )}

              {fileAttachments.length > 0 && (
                <div className="space-y-2">
                  {fileAttachments.map((attachment) => (
                    <a
                      key={attachment.id}
                      href={attachmentDownloadURL(attachment.id)}
                      target="_blank"
                      rel="noreferrer"
                      className="flex items-center justify-between gap-3 rounded-lg border border-border/60 px-3 py-2 text-sm hover:bg-muted/30"
                    >
                      <span className="flex min-w-0 items-center gap-2">
                        <FileText className="h-4 w-4 shrink-0 text-muted-foreground" />
                        <span className="truncate">{attachment.original_filename}</span>
                      </span>
                      <span className="flex shrink-0 items-center gap-2 text-xs text-muted-foreground">
                        {formatBytes(attachment.size_bytes)}
                        <Download className="h-4 w-4" />
                      </span>
                    </a>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        <Card className="h-fit">
          <CardHeader>
            <CardTitle className="text-base">Informações</CardTitle>
          </CardHeader>
          <CardContent className="space-y-3 text-sm">
            <InfoRow label="Cliente" value={item.client_name} />
            <InfoRow label="Status" value={statusLabels[item.status]} />
            <InfoRow label="Tipo" value={item.content_type} />
            <InfoRow label="Data" value={dateFormatter.format(parseDateValue(item.scheduled_date))} />
            <InfoRow label="Anexos" value={String(attachments.length)} />
          </CardContent>
        </Card>
      </div>

      <Dialog open={previewAttachment !== null} onOpenChange={(open) => !open && setPreviewAttachment(null)}>
        <DialogContent className="sm:max-w-[860px]">
          <DialogHeader>
            <DialogTitle>{previewAttachment?.original_filename}</DialogTitle>
            <DialogDescription>Visualização do anexo.</DialogDescription>
          </DialogHeader>
          {previewAttachment && (
            <div className="overflow-hidden rounded-lg border border-border/60 bg-black/5">
              <img
                src={attachmentDownloadURL(previewAttachment.id)}
                alt={previewAttachment.original_filename}
                className="max-h-[70vh] w-full object-contain"
              />
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}

function ReadOnlyField({ label, value, fallback, multiline = false }: { label: string; value: string; fallback: string; multiline?: boolean }) {
  return (
    <div className="grid gap-2">
      <Label>{label}</Label>
      {multiline ? (
        <Textarea value={value || fallback} readOnly className="min-h-[110px]" />
      ) : (
        <Input value={value || fallback} readOnly />
      )}
    </div>
  );
}

function InfoRow({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex items-center justify-between gap-3 border-b border-border/40 pb-2 last:border-b-0 last:pb-0">
      <span className="text-muted-foreground">{label}</span>
      <span className="font-medium text-right">{value}</span>
    </div>
  );
}

function isImageAttachment(attachment: Attachment) {
  return attachment.mime_type.startsWith("image/");
}

function parseDateValue(value: string) {
  const [year, month, day] = value.split("-").map(Number);
  return new Date(year, month - 1, day);
}

function formatBytes(value: number) {
  if (value < 1024) return `${value} B`;
  if (value < 1024 * 1024) return `${Math.round(value / 1024)} KB`;
  return `${(value / 1024 / 1024).toFixed(1)} MB`;
}
