'use client';

import { Image, FileText, Video } from 'lucide-react';
import { useRef, useState } from 'react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';

interface PostComposerProps {
  authorName: string;
  authorRole: 'ADMIN' | 'TEACHER' | 'PARENT';
  onSubmit: (content: string, audience: string, files: File[]) => Promise<void>;
}

const ROLE_AVATAR_CLASS: Record<string, string> = {
  ADMIN: 'bg-violet-100 text-violet-700',
  TEACHER: 'bg-emerald-100 text-emerald-700',
  PARENT: 'bg-orange-100 text-orange-700',
};

const AUDIENCE_OPTIONS = [
  { value: 'ALL', label: 'Herkes' },
  { value: 'TEACHERS_ONLY', label: 'Yalnızca öğretmenler' },
  { value: 'PARENTS_ONLY', label: 'Yalnızca veliler' },
];

export function PostComposer({ authorName, authorRole, onSubmit }: PostComposerProps) {
  const [expanded, setExpanded] = useState(false);
  const [content, setContent] = useState('');
  const [audience, setAudience] = useState('ALL');
  const [files, setFiles] = useState<File[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const fileRef = useRef<HTMLInputElement>(null);
  const videoRef = useRef<HTMLInputElement>(null);
  const docRef = useRef<HTMLInputElement>(null);

  const initials = authorName.split(' ').map((n) => n[0]).join('').toUpperCase().slice(0, 2);

  const handleSubmit = async () => {
    if (!content.trim()) return;
    setIsSubmitting(true);
    setError(null);
    try {
      await onSubmit(content, audience, files);
      setContent('');
      setFiles([]);
      setExpanded(false);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Bir hata oluştu');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="bg-white rounded-2xl border border-gray-200 shadow-sm p-5">
      <div className="flex items-start gap-3">
        <div
          className={cn(
            'w-9 h-9 rounded-full flex items-center justify-center text-xs font-semibold flex-shrink-0',
            ROLE_AVATAR_CLASS[authorRole],
          )}
        >
          {initials}
        </div>
        {!expanded ? (
          <button
            onClick={() => setExpanded(true)}
            className="flex-1 text-left px-4 py-2.5 bg-gray-50 rounded-xl text-sm text-gray-400 hover:bg-gray-100 transition-colors"
          >
            Sınıfınızla bir şey paylaşın…
          </button>
        ) : (
          <div className="flex-1">
            <Textarea
              autoFocus
              value={content}
              onChange={(e) => setContent(e.target.value)}
              placeholder="Ne paylaşmak istersiniz?"
              className="min-h-[100px] resize-none bg-gray-50 border-0 rounded-xl focus-visible:ring-2 focus-visible:ring-violet-500 text-sm"
            />
            {files.length > 0 && (
              <div className="flex flex-wrap gap-2 mt-2">
                {files.map((f, i) => (
                  <span key={i} className="inline-flex items-center gap-1 px-2 py-1 bg-violet-50 text-violet-700 rounded-lg text-xs">
                    {f.name}
                    <button
                      onClick={() => setFiles((p) => p.filter((_, j) => j !== i))}
                      className="ml-1 hover:text-violet-900"
                    >
                      ×
                    </button>
                  </span>
                ))}
              </div>
            )}
          </div>
        )}
      </div>

      {expanded && (
        <div className="flex items-center gap-2 mt-3 pt-3 border-t border-gray-100 flex-wrap">
          <input
            ref={fileRef}
            type="file"
            accept="image/*"
            multiple
            className="hidden"
            onChange={(e) => setFiles((p) => [...p, ...Array.from(e.target.files ?? [])])}
          />
          <input
            ref={docRef}
            type="file"
            accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx"
            multiple
            className="hidden"
            onChange={(e) => setFiles((p) => [...p, ...Array.from(e.target.files ?? [])])}
          />
          <input
            ref={videoRef}
            type="file"
            accept="video/*"
            className="hidden"
            onChange={(e) => setFiles((p) => [...p, ...Array.from(e.target.files ?? [])])}
          />

          <button
            onClick={() => fileRef.current?.click()}
            className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs text-gray-500 hover:bg-gray-100 transition-colors border border-gray-200"
          >
            <Image size={13} /> Fotoğraf
          </button>
          <button
            onClick={() => docRef.current?.click()}
            className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs text-gray-500 hover:bg-gray-100 transition-colors border border-gray-200"
          >
            <FileText size={13} /> Belge
          </button>
          {authorRole === 'ADMIN' && (
            <button
              onClick={() => videoRef.current?.click()}
              className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs text-gray-500 hover:bg-gray-100 transition-colors border border-gray-200"
            >
              <Video size={13} /> Video
            </button>
          )}

          {authorRole === 'ADMIN' && (
            <select
              value={audience}
              onChange={(e) => setAudience(e.target.value)}
              className="ml-auto h-8 text-xs px-2 border border-gray-200 rounded-lg bg-white text-gray-700 focus:outline-none focus:ring-2 focus:ring-violet-500"
            >
              {AUDIENCE_OPTIONS.map((opt) => (
                <option key={opt.value} value={opt.value}>{opt.label}</option>
              ))}
            </select>
          )}

          <Button
            onClick={handleSubmit}
            disabled={!content.trim() || isSubmitting}
            size="sm"
            className={cn(
              'bg-violet-600 hover:bg-violet-700 text-white rounded-xl px-5 text-xs',
              authorRole !== 'ADMIN' && 'ml-auto',
            )}
          >
            {isSubmitting ? 'Gönderiliyor…' : 'Paylaş'}
          </Button>
        </div>
      )}
      {error && (
        <p className="text-xs text-red-500 mt-2 px-1">{error}</p>
      )}
    </div>
  );
}
