import { FC, useState } from 'react';
import { useNavigate, useParams } from 'react-router';
import { Button, Group } from '../../components';
import Breadcrumb from '../../components/Breadcrumb';
import { Dialog } from '../../components/Dialog';
import { approvals as demoApprovals } from '../../demoData/approval';
import { Approval, ApprovalStatus } from '../../types/approval';
import { twx } from '../../utils';
import { ApprovalForm } from './ApprovalForm';
import { ApprovalTable } from './ApprovalTable';
import { UploadFiles } from './UploadFiles';

type FormInputs = {
  title: string;
  department: string;
  description: string;
  status: ApprovalStatus;
};

export const ExternalAuditScene: FC = () => {
  const projectId = useParams().id!;
  const jobId = useParams().jobId!;
  const navigate = useNavigate();
  const [isCollapsedFinalApproval, setIsCollapsedFinalApproval] =
    useState(true);
  const [approvals, setApprovals] = useState<Approval[]>(
    demoApprovals.filter((approval) => approval.jobId === jobId),
  );
  const [openDialog, setOpenDialog] = useState<'info' | 'uploadFiles' | null>(
    null,
  );
  const [selectedApproval, setSelectedApproval] = useState<Approval | null>(
    null,
  );

  const canSubmitFinalApproval = approvals.every(
    (approval) => approval.status === 'Approved',
  );

  const handleCreate = (data: FormInputs) => {
    const approval: Approval = {
      approvalId: Date.now().toString(),
      jobId: jobId,
      title: data.title,
      description: data.description,
      department: data.department,
      status: 'Pending',
      createdAt: new Date().toISOString(),
      files: [],
    };
    setApprovals([...approvals, approval]);
    setOpenDialog(null);
  };

  const handleEdit = (data: FormInputs) => {
    if (selectedApproval) {
      const updatedApprovals = approvals.map((approval) => {
        if (approval.approvalId === selectedApproval.approvalId) {
          return {
            ...approval,
            title: data.title,
            department: data.department,
            description: data.description,
            status: data.status,
          };
        }
        return approval;
      });
      setApprovals(updatedApprovals);
      const updatedApproval = updatedApprovals.find(
        (approval) => approval.approvalId === selectedApproval.approvalId,
      );
      if (updatedApproval) {
        setSelectedApproval(updatedApproval);
      }
      setOpenDialog(null);
    }
  };

  const handleFileUpload = (files: FileList) => {
    if (selectedApproval) {
      const updatedApprovals = approvals.map((approval) => {
        if (approval.approvalId === selectedApproval.approvalId) {
          return {
            ...approval,
            files: [...approval.files, ...Array.from(files)],
          };
        }
        return approval;
      });
      setApprovals(updatedApprovals);
      const updatedApproval = updatedApprovals.find(
        (approval) => approval.approvalId === selectedApproval.approvalId,
      );
      if (updatedApproval) {
        setSelectedApproval(updatedApproval);
      }
    }
  };

  const handleDeleteFile = (index: number) => {
    if (selectedApproval) {
      const updatedApprovals = approvals.map((approval) => {
        if (approval.approvalId === selectedApproval.approvalId) {
          return {
            ...approval,
            files: approval.files.filter((_, i) => i !== index),
          };
        }
        return approval;
      });
      setApprovals(updatedApprovals);
    }
  };

  return (
    <>
      <Dialog
        key={selectedApproval?.approvalId}
        open={openDialog !== null}
        onRequestClose={() => setOpenDialog(null)}
        className="w-[600px] flex flex-col gap-4 rounded-lg bg-white p-6 dark:bg-gray-800"
      >
        <div className="text-2xl font-bold">Approval</div>
        <div className="flex flex-col gap-2">
          {openDialog === 'info' && (
            <ApprovalForm
              key={selectedApproval?.approvalId}
              approval={selectedApproval ?? undefined}
              handleSubmit={selectedApproval ? handleEdit : handleCreate}
            />
          )}
          <div className="flex flex-col gap-2 border-t pt-4">
            <p className="font-bold">Status</p>
            <select
              className="mb-2 w-full border rounded px-3 py-2"
              defaultValue={selectedApproval?.status}
              onChange={(e) => {
                if (selectedApproval) {
                  handleEdit({
                    ...selectedApproval,
                    status: e.target.value as ApprovalStatus,
                  });
                }
              }}
            >
              <option value="Pending">Pending</option>
              <option value="Approved">Approved</option>
              <option value="Rejected">Rejected</option>
            </select>
          </div>
        </div>
        {openDialog === 'uploadFiles' && (
          <UploadFiles
            key={selectedApproval?.approvalId}
            approval={selectedApproval ?? undefined}
            handleFileUpload={handleFileUpload}
            handleDeleteFile={handleDeleteFile}
          />
        )}
      </Dialog>
      <Group className="w-full gap-2">
        <Breadcrumb
          crumbs={[
            {
              label: 'Project Record',
              onClick: () => navigate('/project-record'),
            },
            {
              label: projectId || '',
              onClick: () => navigate(`/project-record/${projectId}`),
            },
            { label: `${jobId} - External Audit` },
          ]}
        />
      </Group>
      <div className="mt-2 flex flex-col gap-2">
        <div className="w-full flex flex-col gap-2 rounded-lg bg-white p-4 dark:bg-gray-800">
          <div className="text-lg font-bold">Approval</div>
          <div className="onClick={() => setIsFormVisible(!isFormVisible)} flex items-center justify-between">
            <button
              onClick={() => {
                setSelectedApproval(null);
                setOpenDialog('info');
              }}
              className="hover:bg-blue-600 rounded bg-blue-5 px-4 py-2 text-white"
            >
              Create Approval
            </button>
          </div>
          {/* Approval List */}
          <ApprovalTable
            approvals={approvals}
            onSelectApproval={(approval, action) => {
              if (action === 'edit') {
                setSelectedApproval(approval);
                setOpenDialog('info');
              } else if (action === 'files') {
                setSelectedApproval(approval);
                setOpenDialog('uploadFiles');
              } else if (action === 'delete') {
                setApprovals(
                  approvals.filter((a) => a.approvalId !== approval.approvalId),
                );
              }
            }}
            allowDelete={true}
          />
        </div>
        <div
          className={twx(
            'flex flex-col w-full gap-2 bg-white dark:bg-gray-800 p-4 rounded-lg overflow-hidden transition-all duration-300 h-112',
            { 'opacity-50': !canSubmitFinalApproval },
            { 'h-20': isCollapsedFinalApproval },
          )}
        >
          <div
            className="flex cursor-pointer"
            onClick={() =>
              setIsCollapsedFinalApproval(!isCollapsedFinalApproval)
            }
          >
            <div className="flex flex-col gap-2">
              <div className="text-lg font-bold">Final Approval</div>
              <div className="text-red-500 text-sm text-black/60">
                All approvals must be approved before submitting the final
                approval
              </div>
            </div>
            <div className="ml-auto flex items-center gap-2">
              <div className="i-mdi-chevron-down text-2xl" />
            </div>
          </div>
          <div className="flex flex-col gap-4 transition-opacity duration-300">
            <FinalApprovalForm />
            <Button className="hover:bg-blue-600 w-full rounded bg-blue-5 text-white">
              Approve Complete
            </Button>
          </div>
        </div>
      </div>
    </>
  );
};

const FinalApprovalForm: FC = () => {
  const [finalApproval] = useState<Approval | null>({
    approvalId: 'finalApproval',
    jobId: 'finalApproval',
    title: 'Final Approval',
    description: 'Final Approval',
    department: 'Final Approval',
    status: 'Pending',
    createdAt: new Date().toISOString(),
    files: [],
  });
  const [finalApprovalFile, setFinalApprovalFile] = useState<File | null>(null);

  return (
    <div className="flex flex-col gap-4">
      <div className="flex gap-4">
        <button
          className="hover:bg-blue-600 rounded bg-blue-5 px-4 py-2 text-white"
          onClick={() => {
            console.log('下载模板');
          }}
        >
          Download final approval form
        </button>

        <input
          type="file"
          onChange={(e) => {
            if (e.target.files?.[0]) {
              setFinalApprovalFile(e.target.files[0]);
            }
          }}
          className="hover:file:bg-blue-600 file:mr-4 file:border-0 file:rounded file:bg-blue-5 file:px-4 file:py-2 file:text-white"
        />
      </div>

      {finalApprovalFile && (
        <div className="flex items-center gap-2 rounded bg-gray-100 p-2 dark:bg-gray-700">
          <span>{finalApprovalFile.name}</span>
          <button
            onClick={() => setFinalApprovalFile(null)}
            className="text-red-500 hover:text-red-600"
          >
            Delete
          </button>
        </div>
      )}

      <div>
        <ApprovalForm
          key={finalApproval?.approvalId}
          approval={finalApproval ?? undefined}
          handleSubmit={() => {}}
        />
      </div>
    </div>
  );
};
