'use client';

import React, { useEffect, useState } from 'react';
import { App, Button, Form, Input, Modal, Popconfirm, Tooltip, Upload } from 'antd';
import type { UploadFile } from 'antd/es/upload/interface';
import dayjs from 'dayjs';
import { Icon } from '../ui/Icon';
import { UserAvatar } from '../ui/UserAvatar';
import { type FileRecord, filesApi, FILES_CHANGED_EVENT } from '../../lib/files';

function formatFileSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

function getFileExtBadge(fileName: string): { ext: string; bg: string; color: string } {
  const parts = fileName.split('.');
  const ext = (parts.length > 1 ? parts.pop() : 'FILE')?.toUpperCase().slice(0, 4) || 'FILE';

  switch (ext) {
    case 'PDF':
      return { ext, bg: '#FEE2E2', color: '#DC2626' };
    case 'DOC':
    case 'DOCX':
      return { ext, bg: '#DBEAFE', color: '#2563EB' };
    case 'XLS':
    case 'XLSX':
    case 'CSV':
      return { ext, bg: '#DCFCE7', color: '#16A34A' };
    case 'ZIP':
    case 'RAR':
    case 'TAR':
    case '7Z':
      return { ext, bg: '#FEF3C7', color: '#D97706' };
    default:
      return { ext, bg: '#F1F5F9', color: '#475569' };
  }
}

export function DealLinkedFiles({ dealId, onCountChange }: { dealId: string; onCountChange?: (count: number) => void }) {
  const { message } = App.useApp();
  const [files, setFiles] = useState<FileRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [uploadModalOpen, setUploadModalOpen] = useState(false);
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [submitting, setSubmitting] = useState(false);
  const [reload, setReload] = useState(0);
  const [downloadingId, setDownloadingId] = useState<string | null>(null);
  const [form] = Form.useForm();

  useEffect(() => {
    let active = true;
    const load = async () => {
      await Promise.resolve();
      if (!active) return;
      setLoading(true);
      try {
        const res = await filesApi.list({ dealId, limit: 100 });
        if (!active) return;
        setFiles(res.data);
        onCountChange?.(res.meta.total);
      } catch {
        if (!active) return;
        setFiles([]);
      } finally {
        if (active) setLoading(false);
      }
    };
    void load();
    const handleFilesChanged = () => {
      if (active) setReload((n) => n + 1);
    };
    window.addEventListener(FILES_CHANGED_EVENT, handleFilesChanged);
    return () => {
      active = false;
      window.removeEventListener(FILES_CHANGED_EVENT, handleFilesChanged);
    };
  }, [dealId, reload, onCountChange]);

  const handleDownload = async (file: FileRecord) => {
    setDownloadingId(file.id);
    try {
      await filesApi.triggerBrowserDownload(file.id, file.fileName);
      message.success('Download started');
    } catch (err) {
      message.error(err instanceof Error ? err.message : 'Download failed');
    } finally {
      setDownloadingId(null);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await filesApi.delete(id);
      message.success('File deleted');
      setReload((n) => n + 1);
    } catch (err) {
      message.error(err instanceof Error ? err.message : 'Failed to delete file');
    }
  };

  const handleUploadSubmit = async (values: { description?: string }) => {
    const chosen = fileList[0];
    const rawFile = (chosen?.originFileObj || (chosen as unknown as File)) as File;
    if (!chosen || !rawFile || typeof rawFile.slice !== 'function') {
      message.error('Please choose a file to upload');
      return;
    }

    if (rawFile.size > 10 * 1024 * 1024) {
      message.error('File size exceeds the 10 MB limit');
      return;
    }

    setSubmitting(true);
    try {
      await filesApi.upload(rawFile, {
        dealId,
        description: values.description?.trim() || undefined,
      });
      message.success('Document uploaded successfully');
      setUploadModalOpen(false);
      setFileList([]);
      form.resetFields();
      setReload((n) => n + 1);
    } catch (err) {
      message.error(err instanceof Error ? err.message : 'Upload failed');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="pt-2">
      <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
        <div>
          <h3 className="m-0 text-[15px] font-bold text-[var(--tcx-text)]">Deal Documents & Files</h3>
          <p className="m-0 mt-0.5 text-[12.5px] text-[var(--tcx-muted)]">Proposals, client requirements, SOWs, and contracts attached directly to this deal.</p>
        </div>
        <Button
          type="primary"
          icon={<Icon name="upload" size={13} />}
          onClick={() => {
            setFileList([]);
            form.resetFields();
            setUploadModalOpen(true);
          }}
        >
          Upload document
        </Button>
      </div>

      {loading ? (
        <div className="py-8 text-center text-xs text-slate-400">Loading documents...</div>
      ) : files.length === 0 ? (
        <div className="rounded-xl border border-dashed border-[var(--tcx-border)] p-8 text-center">
          <p className="m-0 text-[14px] font-semibold text-[var(--tcx-text)]">No files attached to this deal</p>
          <p className="m-0 mt-1 text-[12.5px] text-[var(--tcx-muted)]">Upload client requirements, signed SOWs, or technical specifications.</p>
          <Button
            type="primary"
            icon={<Icon name="upload" size={13} />}
            onClick={() => {
              setFileList([]);
              form.resetFields();
              setUploadModalOpen(true);
            }}
            className="mt-3"
          >
            Upload first document
          </Button>
        </div>
      ) : (
        <div className="overflow-x-auto rounded-xl border border-[var(--tcx-border)]">
          <table className="w-full text-left text-[13px]">
            <thead className="border-b border-[var(--tcx-border)] bg-[var(--tcx-sunken)] text-[var(--tcx-muted)]">
              <tr>
                <th className="p-3">Document</th>
                <th className="p-3">Size</th>
                <th className="p-3">Uploaded by</th>
                <th className="p-3">Date</th>
                <th className="p-3 text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[var(--tcx-border)]">
              {files.map((f) => {
                const badge = getFileExtBadge(f.fileName);
                return (
                  <tr key={f.id} className="hover:bg-[var(--tcx-sunken)]">
                    <td className="p-3">
                      <div className="flex items-start gap-2.5">
                        <span className="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded text-[10px] font-bold" style={{ backgroundColor: badge.bg, color: badge.color }}>
                          {badge.ext}
                        </span>
                        <div className="min-w-0">
                          <button type="button" onClick={() => window.open(filesApi.getViewUrl(f.id), '_blank')} className="text-left font-semibold text-slate-800 text-sm hover:text-blue-600 hover:underline dark:text-slate-100 block max-w-sm truncate cursor-pointer" title={f.fileName}>
                            {f.fileName}
                          </button>
                          {f.description ? (
                            <div className="text-[12px] text-slate-500 dark:text-slate-400 mt-0.5 max-w-sm truncate" title={f.description}>
                              {f.description}
                            </div>
                          ) : null}
                        </div>
                      </div>
                    </td>
                    <td className="p-3 font-mono text-xs text-slate-500 whitespace-nowrap">{formatFileSize(f.sizeBytes)}</td>
                    <td className="p-3">
                      {f.uploadedBy ? (
                        <div className="flex items-center gap-1.5 text-xs text-slate-700 dark:text-slate-200">
                          <UserAvatar name={f.uploadedBy.name} size={20} />
                          <span>{f.uploadedBy.name}</span>
                        </div>
                      ) : (
                        <span className="text-slate-400 text-xs">User</span>
                      )}
                    </td>
                    <td className="p-3 text-xs text-slate-500 whitespace-nowrap">{dayjs(f.createdAt).format('D MMM YYYY')}</td>
                    <td className="p-3 text-right">
                      <div className="flex items-center justify-end gap-1">
                        <Tooltip title="View / Open">
                          <Button type="text" size="small" icon={<Icon name="eye" size={14} />} onClick={() => window.open(filesApi.getViewUrl(f.id), '_blank')} aria-label="View" />
                        </Tooltip>
                        <Tooltip title="Download">
                          <Button type="text" size="small" loading={downloadingId === f.id} icon={<Icon name="download" size={14} />} onClick={() => handleDownload(f)} aria-label="Download" />
                        </Tooltip>
                        <Popconfirm title="Delete this document?" description="This action cannot be undone." onConfirm={() => handleDelete(f.id)} okText="Delete" cancelText="Cancel" okButtonProps={{ danger: true }}>
                          <Button type="text" danger size="small" icon={<Icon name="trash" size={14} />} aria-label="Delete" />
                        </Popconfirm>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      {/* Upload Document Modal */}
      <Modal
        title="Upload Deal Document"
        open={uploadModalOpen}
        onCancel={() => {
          if (!submitting) {
            setUploadModalOpen(false);
            setFileList([]);
            form.resetFields();
          }
        }}
        footer={null}
        destroyOnHidden
      >
        <Form form={form} layout="vertical" onFinish={handleUploadSubmit} className="mt-4">
          {fileList.length === 0 ? (
            <Form.Item label="File (up to 10 MB)" required>
              <Upload.Dragger
                fileList={fileList}
                showUploadList={false}
                beforeUpload={(file) => {
                  if (file.size > 10 * 1024 * 1024) {
                    message.error('File size must not exceed 10 MB');
                    return Upload.LIST_IGNORE;
                  }
                  setFileList([file as unknown as UploadFile]);
                  return false;
                }}
                accept=".pdf,.doc,.docx,.xls,.xlsx,.csv,.png,.jpg,.jpeg,.webp,.svg,.zip,.tar,.gz"
                maxCount={1}
                className="!bg-slate-50/50 hover:!bg-blue-50/20 !border-dashed !border-slate-300 hover:!border-blue-500 !rounded-lg"
              >
                <div className="py-4 px-2 text-center">
                  <p className="flex justify-center text-slate-400 mb-1.5">
                    <Icon name="upload" size={24} />
                  </p>
                  <p className="text-xs font-medium text-slate-700 dark:text-slate-200">
                    <span className="text-blue-600 font-semibold hover:underline">Click to browse</span> or drag and drop file here
                  </p>
                  <p className="text-[11px] text-slate-400 mt-1">Supports PDF, DOCX, XLSX, Images, ZIP up to 10 MB</p>
                </div>
              </Upload.Dragger>
            </Form.Item>
          ) : (
            <Form.Item label="Selected File" required>
              <div className="flex items-center justify-between rounded-lg border border-slate-200 bg-slate-50/60 px-3.5 py-2.5 dark:border-slate-800 dark:bg-slate-900/60">
                <div className="flex items-center gap-3 min-w-0">
                  <div
                    className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md font-bold text-xs uppercase"
                    style={{
                      backgroundColor: getFileExtBadge(fileList[0].name || '').bg,
                      color: getFileExtBadge(fileList[0].name || '').color,
                    }}
                  >
                    {getFileExtBadge(fileList[0].name || '').ext}
                  </div>
                  <div className="min-w-0">
                    <div className="truncate text-xs font-semibold text-slate-800 dark:text-slate-100" title={fileList[0].name}>
                      {fileList[0].name}
                    </div>
                    <div className="flex items-center gap-2 mt-0.5">
                      <span className="font-mono text-[11px] text-slate-400">{fileList[0].size ? formatFileSize(fileList[0].size) : 'Ready'}</span>
                      <span className="text-emerald-600 text-[11px] font-medium">✓ Ready to upload</span>
                    </div>
                  </div>
                </div>
                <Button type="text" danger size="small" icon={<Icon name="trash" size={14} />} onClick={() => setFileList([])}>
                  Remove
                </Button>
              </div>
            </Form.Item>
          )}

          <Form.Item name="description" label="Description / Purpose (Optional)">
            <Input.TextArea rows={3} placeholder="Enter file description or notes" />
          </Form.Item>

          <div className="flex justify-end gap-2 pt-3 border-t border-slate-100 dark:border-slate-800">
            <Button
              onClick={() => {
                setUploadModalOpen(false);
                setFileList([]);
                form.resetFields();
              }}
              disabled={submitting}
            >
              Cancel
            </Button>
            <Button type="primary" htmlType="submit" loading={submitting} disabled={fileList.length === 0}>
              Upload Document
            </Button>
          </div>
        </Form>
      </Modal>
    </div>
  );
}
