import { useState, useRef, useCallback } from 'react';
import { router } from '@inertiajs/react';
import { AppLayout } from '@/Components/Layout/AppLayout';

type Homework = {
  id: number;
  title: string;
  description: string | null;
  dueAt: string;
  dueAtRaw: string | null;
  allowFileUpload: boolean;
  classroom: string;
  subject: string;
  submitted: boolean;
  submissionBody: string | null;
  submissionFile: string | null;
  submissionStatus: string | null;
  submittedAt: string | null;
};

type UploadFile = {
  file: File;
  preview: string | null;
};

const submissionStatusLabel: Record<string, string> = {
  submitted: 'ارسال شده',
  late: 'دیر ارسال',
  reviewed: 'بررسی شد',
  returned: 'بازگشت داده شد',
};

function getHomeworkStatus(hw: Homework): 'submitted' | 'late_submitted' | 'missing' | 'pending' {
  if (hw.submitted) {
    if (hw.dueAtRaw && hw.submittedAt) {
      const due = new Date(hw.dueAtRaw);
      return new Date(hw.submittedAt) > due ? 'late_submitted' : 'submitted';
    }
    return 'submitted';
  }
  if (hw.dueAtRaw && new Date(hw.dueAtRaw) < new Date()) return 'missing';
  return 'pending';
}

function isImageFile(file: File): boolean {
  return file.type.startsWith('image/');
}

function FileUploadZone({
  onFile,
  currentFile,
  onClear,
  existingFileName,
}: {
  onFile: (f: File) => void;
  currentFile: UploadFile | null;
  onClear: () => void;
  existingFileName: string | null;
}) {
  const fileRef = useRef<HTMLInputElement>(null);
  const cameraRef = useRef<HTMLInputElement>(null);
  const [dragging, setDragging] = useState(false);

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setDragging(false);
    const f = e.dataTransfer.files[0];
    if (f) onFile(f);
  }, [onFile]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const f = e.target.files?.[0];
    if (f) onFile(f);
    e.target.value = '';
  };

  return (
    <div>
      {/* Hidden inputs */}
      <input
        ref={fileRef}
        type="file"
        accept="image/*,.pdf,.doc,.docx,.txt"
        style={{ display: 'none' }}
        onChange={handleChange}
      />
      <input
        ref={cameraRef}
        type="file"
        accept="image/*"
        capture="environment"
        style={{ display: 'none' }}
        onChange={handleChange}
      />

      {currentFile ? (
        /* Preview */
        <div style={{
          display: 'flex', alignItems: 'center', gap: '0.75rem',
          background: 'var(--color-primary-soft)', border: '1.5px solid var(--color-primary)',
          borderRadius: 'var(--radius-md)', padding: '0.7rem 1rem',
        }}>
          {currentFile.preview ? (
            <img
              src={currentFile.preview}
              alt=""
              style={{ width: 52, height: 52, objectFit: 'cover', borderRadius: 8, flexShrink: 0 }}
            />
          ) : (
            <div style={{ width: 52, height: 52, borderRadius: 8, background: 'var(--color-bg-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <i className="bi bi-file-earmark-text" style={{ fontSize: '1.5rem', color: 'var(--color-primary)' }} />
            </div>
          )}
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontWeight: 600, fontSize: '0.875rem', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {currentFile.file.name}
            </div>
            <div style={{ fontSize: '0.75rem', color: 'var(--color-text-muted)' }}>
              {(currentFile.file.size / 1024 / 1024).toFixed(1)} MB
            </div>
          </div>
          <button
            type="button"
            onClick={onClear}
            style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--color-danger)', fontSize: '1.1rem', padding: '0.25rem', flexShrink: 0 }}
            title="حذف فایل"
          >
            <i className="bi bi-x-circle-fill" />
          </button>
        </div>
      ) : (
        /* Drop zone */
        <div
          onDragEnter={() => setDragging(true)}
          onDragLeave={() => setDragging(false)}
          onDragOver={e => e.preventDefault()}
          onDrop={handleDrop}
          onClick={() => fileRef.current?.click()}
          style={{
            border: `2px dashed ${dragging ? 'var(--color-primary)' : 'var(--color-border)'}`,
            borderRadius: 'var(--radius-md)',
            padding: '1.25rem 1rem',
            textAlign: 'center',
            cursor: 'pointer',
            background: dragging ? 'var(--color-primary-soft)' : 'var(--color-bg-soft)',
            transition: 'all 0.15s',
          }}
        >
          <i className="bi bi-cloud-upload" style={{ fontSize: '1.8rem', color: dragging ? 'var(--color-primary)' : 'var(--color-text-muted)', display: 'block', marginBottom: '0.3rem' }} />
          <div style={{ fontSize: '0.85rem', color: 'var(--color-text-muted)', marginBottom: '0.6rem' }}>
            {existingFileName
              ? <><i className="bi bi-paperclip" style={{ marginLeft: '0.3rem' }} />فایل قبلی: <strong>{existingFileName}</strong> — برای تغییر کلیک کنید</>
              : 'فایل را اینجا بکشید یا کلیک کنید'}
          </div>
          <div style={{ display: 'flex', justifyContent: 'center', gap: '0.5rem', flexWrap: 'wrap' }} onClick={e => e.stopPropagation()}>
            <button
              type="button"
              className="btn btn-ghost btn-sm"
              onClick={() => fileRef.current?.click()}
            >
              <i className="bi bi-folder2-open" /> انتخاب فایل
            </button>
            <button
              type="button"
              className="btn btn-ghost btn-sm"
              onClick={() => cameraRef.current?.click()}
            >
              <i className="bi bi-camera" /> دوربین
            </button>
          </div>
          <div style={{ fontSize: '0.73rem', color: 'var(--color-text-muted)', marginTop: '0.4rem' }}>
            تصویر، PDF، Word — حداکثر ۱۰ مگابایت
          </div>
        </div>
      )}
    </div>
  );
}

function HomeworkForm({
  hw,
  onCancel,
}: {
  hw: Homework;
  onCancel: () => void;
}) {
  const isEdit = hw.submitted;
  const [body, setBody] = useState(hw.submissionBody ?? '');
  const [uploadFile, setUploadFile] = useState<UploadFile | null>(null);
  const [processing, setProcessing] = useState(false);

  const handleFile = useCallback((f: File) => {
    const preview = isImageFile(f) ? URL.createObjectURL(f) : null;
    setUploadFile({ file: f, preview });
  }, []);

  const clearFile = useCallback(() => {
    if (uploadFile?.preview) URL.revokeObjectURL(uploadFile.preview);
    setUploadFile(null);
  }, [uploadFile]);

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (processing) return;
    setProcessing(true);

    const fd = new FormData();
    fd.append('body', body);
    if (uploadFile) fd.append('file', uploadFile.file);
    if (isEdit) fd.append('_method', 'PUT');

    router.post(
      `/student/homeworks/${hw.id}`,
      fd,
      {
        forceFormData: true,
        onSuccess: () => {
          if (uploadFile?.preview) URL.revokeObjectURL(uploadFile.preview);
          onCancel();
        },
        onError: () => setProcessing(false),
        onFinish: () => setProcessing(false),
      }
    );
  }

  return (
    <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '0.85rem' }}>
      <div>
        <label className="form-label">
          <i className="bi bi-pencil" style={{ marginLeft: '0.3rem' }} />
          {isEdit ? 'ویرایش پاسخ' : 'پاسخ شما'}
          <span style={{ fontWeight: 400, color: 'var(--color-text-muted)', marginRight: '0.3rem' }}>(اختیاری)</span>
        </label>
        <textarea
          className="form-control"
          rows={4}
          placeholder="پاسخ، توضیحات یا متن تکلیف را اینجا بنویسید..."
          value={body}
          onChange={e => setBody(e.target.value)}
          maxLength={5000}
          style={{ minHeight: 100 }}
        />
        {body.length > 4500 && (
          <div style={{ fontSize: '0.75rem', color: 'var(--color-warning)', marginTop: '0.2rem' }}>
            {body.length}/5000 کاراکتر
          </div>
        )}
      </div>

      {hw.allowFileUpload && (
        <div>
          <label className="form-label">
            <i className="bi bi-paperclip" style={{ marginLeft: '0.3rem' }} />
            فایل ضمیمه
            <span style={{ fontWeight: 400, color: 'var(--color-text-muted)', marginRight: '0.3rem' }}>(اختیاری)</span>
          </label>
          <FileUploadZone
            onFile={handleFile}
            currentFile={uploadFile}
            onClear={clearFile}
            existingFileName={isEdit ? hw.submissionFile : null}
          />
        </div>
      )}

      <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap' }}>
        <button
          type="submit"
          className="btn btn-primary"
          disabled={processing || (!body.trim() && !uploadFile && !hw.allowFileUpload)}
        >
          <i className={`bi ${processing ? 'bi-hourglass-split' : isEdit ? 'bi-pencil-check' : 'bi-send'}`} />
          {processing ? 'در حال ارسال...' : isEdit ? 'ذخیره تغییرات' : 'ارسال تکلیف'}
        </button>
        <button
          type="button"
          className="btn btn-ghost"
          onClick={onCancel}
          disabled={processing}
        >
          انصراف
        </button>
      </div>
    </form>
  );
}

export default function StudentHomeworks({ homeworks }: { homeworks: Homework[] }) {
  const [activeId, setActiveId] = useState<number | null>(null);

  return (
    <AppLayout title="تکالیف">
      <div className="page-stack">
        <section className="section-header">
          <div>
            <h2>
              <i className="bi bi-journal-check" style={{ marginLeft: '0.5rem', color: 'var(--color-primary)' }} />
              تکالیف
            </h2>
            <p>تکالیف منتشرشده برای کلاس‌های شما</p>
          </div>
        </section>

        {homeworks.length === 0 ? (
          <section className="panel-card">
            <div style={{ textAlign: 'center', padding: '2rem 1rem' }}>
              <div className="icon-badge" style={{ width: 56, height: 56, fontSize: '1.5rem', margin: '0 auto 1rem' }}>
                <i className="bi bi-journal-check" />
              </div>
              <h2>تکلیفی وجود ندارد</h2>
              <p>در حال حاضر تکلیف فعالی برای کلاس‌های شما ثبت نشده است.</p>
            </div>
          </section>
        ) : (
          <div className="card-grid">
            {homeworks.map(hw => {
              const hwStatus = getHomeworkStatus(hw);
              const isMissing = hwStatus === 'missing';
              const isLate = hwStatus === 'late_submitted';
              const isOpen = activeId === hw.id;

              return (
                <article
                  key={hw.id}
                  className="panel-card"
                  style={{
                    display: 'flex',
                    flexDirection: 'column',
                    gap: '0.75rem',
                    borderColor: isMissing ? 'var(--color-danger)' : hw.submitted ? 'var(--color-primary)' : undefined,
                    background: isMissing ? 'rgba(239,68,68,0.04)' : undefined,
                  }}
                >
                  {/* Header */}
                  <div style={{ display: 'flex', alignItems: 'flex-start', gap: '0.75rem' }}>
                    <span className="icon-badge" style={{ flexShrink: 0, background: isMissing ? 'rgba(239,68,68,0.1)' : hw.submitted ? 'var(--color-primary-soft)' : undefined }}>
                      <i className={`bi ${isMissing ? 'bi-x-circle' : hw.submitted ? 'bi-check-circle-fill' : 'bi-journal-check'}`}
                         style={{ color: isMissing ? 'var(--color-danger)' : hw.submitted ? 'var(--color-primary)' : undefined }}
                      />
                    </span>
                    <div style={{ flex: 1 }}>
                      <h3 style={{ margin: 0, fontSize: '1rem' }}>{hw.title}</h3>
                      <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap', marginTop: '0.2rem' }}>
                        <span style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>
                          <i className="bi bi-door-open" style={{ marginLeft: '0.25rem' }} />{hw.classroom}
                        </span>
                        {hw.subject !== '—' && (
                          <span style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>
                            <i className="bi bi-book" style={{ marginLeft: '0.25rem' }} />{hw.subject}
                          </span>
                        )}
                      </div>
                      {hw.description && (
                        <p style={{ margin: '0.4rem 0 0', fontSize: '0.875rem', color: 'var(--color-text-muted)', lineHeight: 1.5 }}>
                          {hw.description}
                        </p>
                      )}
                    </div>
                    {/* Status badge */}
                    {isMissing && (
                      <span className="badge badge-danger" style={{ flexShrink: 0, whiteSpace: 'nowrap' }}>
                        <i className="bi bi-x-circle-fill" /> نفرستادی
                      </span>
                    )}
                    {isLate && (
                      <span className="badge badge-warning" style={{ flexShrink: 0, whiteSpace: 'nowrap' }}>
                        <i className="bi bi-clock-history" /> دیر ارسال
                      </span>
                    )}
                    {!isMissing && !isLate && hw.submitted && hw.submissionStatus && (
                      <span className="badge badge-success" style={{ flexShrink: 0, whiteSpace: 'nowrap' }}>
                        <i className="bi bi-check2-circle" /> {submissionStatusLabel[hw.submissionStatus] ?? hw.submissionStatus}
                      </span>
                    )}
                  </div>

                  {/* Due date */}
                  {hw.dueAt !== '—' && (
                    <div style={{ fontSize: '0.82rem', color: isMissing ? 'var(--color-danger)' : 'var(--color-text-muted)', display: 'flex', alignItems: 'center', gap: '0.3rem' }}>
                      <i className="bi bi-calendar-x" />
                      مهلت تحویل: {hw.dueAt}
                    </div>
                  )}

                  {/* Submitted info bar */}
                  {hw.submitted && !isOpen && (
                    <div style={{
                      display: 'flex', alignItems: 'center', gap: '0.5rem',
                      background: 'var(--color-primary-soft)',
                      border: '1px solid var(--color-primary)',
                      borderRadius: 'var(--radius-sm)',
                      padding: '0.55rem 0.9rem', fontSize: '0.875rem',
                    }}>
                      <i className="bi bi-check-circle-fill" style={{ color: 'var(--color-primary)' }} />
                      <span style={{ fontWeight: 600, color: 'var(--color-primary)' }}>ارسال شده</span>
                      {hw.submittedAt && (
                        <span style={{ fontWeight: 400, color: 'var(--color-text-muted)', fontSize: '0.8rem', marginRight: 'auto' }}>
                          {hw.submittedAt}
                        </span>
                      )}
                      {hw.submissionFile && (
                        <span style={{ fontSize: '0.78rem', color: 'var(--color-text-muted)', display: 'flex', alignItems: 'center', gap: '0.2rem' }}>
                          <i className="bi bi-paperclip" /> {hw.submissionFile}
                        </span>
                      )}
                    </div>
                  )}

                  {/* Form or action buttons */}
                  {isOpen ? (
                    <HomeworkForm hw={hw} onCancel={() => setActiveId(null)} />
                  ) : (
                    <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap' }}>
                      {hw.submitted ? (
                        <button
                          className="btn btn-ghost btn-sm"
                          onClick={() => setActiveId(hw.id)}
                          style={{ color: 'var(--color-primary)' }}
                        >
                          <i className="bi bi-pencil" /> ویرایش تکلیف
                        </button>
                      ) : (
                        <button
                          className="btn btn-primary"
                          style={{ flex: 1, justifyContent: 'center' }}
                          onClick={() => setActiveId(hw.id)}
                        >
                          <i className="bi bi-send" /> ارسال تکلیف
                        </button>
                      )}
                    </div>
                  )}
                </article>
              );
            })}
          </div>
        )}
      </div>
    </AppLayout>
  );
}
