'use client';

import { useState } from 'react';
import { useForm } from 'react-hook-form';

export interface IncidentFormValues {
  title: string;
  incidentType: string;
  incidentArea: string;
  mediaLink: string;
  description: string;
  mediaFiles: FileList | null;
}

interface IncidentFormProps {
  onSubmit: (data: IncidentFormValues) => Promise<boolean> | boolean;
}

const errorClassName = 'text-xs text-red-600 mt-1';

export function IncidentForm({ onSubmit }: IncidentFormProps) {
  const [mediaPreviews, setMediaPreviews] = useState<string[]>([]);
  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
    reset,
  } = useForm<IncidentFormValues>({
    defaultValues: {
      title: '',
      incidentType: '',
      incidentArea: 'ঢাকা-১০',
      mediaLink: '',
      description: '',
      mediaFiles: null,
    },
  });

  const handleMediaChange = (files: FileList | null) => {
    if (!files || files.length === 0) {
      setMediaPreviews([]);
      return;
    }

    const previews: string[] = [];
    Array.from(files).forEach((file) => {
      const reader = new FileReader();
      reader.onload = (event) => {
        if (typeof event.target?.result === 'string') {
          previews.push(event.target.result);
          if (previews.length === files.length) {
            setMediaPreviews(previews);
          }
        }
      };
      reader.readAsDataURL(file);
    });
  };

  const submitForm = async (data: IncidentFormValues) => {
    const result = await onSubmit(data);
    if (result !== false) {
      reset();
      setMediaPreviews([]);
    }
  };

  return (
    <form className="space-y-4 sm:space-y-6" onSubmit={handleSubmit(submitForm)}>
      <div>
        <label className="block text-xs sm:text-sm font-bold text-gray-700 mb-1.5 sm:mb-2">
          শিরোনাম <span className="text-red-500">*</span>
        </label>
        <input
          type="text"
          placeholder="ঘটনার সারসংক্ষেপ"
          className="w-full px-3 py-2 sm:px-4 sm:py-3 rounded-lg sm:rounded-xl border border-gray-200 text-sm focus:border-red-500 focus:ring-2 focus:ring-red-100 outline-none transition"
          {...register('title', {
            required: 'শিরোনাম আবশ্যক',
            minLength: { value: 5, message: 'কমপক্ষে ৫ অক্ষর লিখুন' },
          })}
        />
        {errors.title && <p className={errorClassName}>{errors.title.message}</p>}
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
        <div>
          <label className="block text-xs sm:text-sm font-bold text-gray-700 mb-1.5 sm:mb-2">
            অভিযোগের ধরন <span className="text-red-500">*</span>
          </label>
          <select
            className="w-full px-3 py-2 sm:px-4 sm:py-3 rounded-lg sm:rounded-xl border border-gray-200 text-sm focus:border-red-500 focus:ring-2 focus:ring-red-100 outline-none transition bg-white"
            {...register('incidentType', { required: 'অভিযোগের ধরন নির্বাচন করুন' })}
          >
            <option value="">নির্বাচন করুন...</option>
            <option value="শারীরিক সহিংসতা">
              শারীরিক সহিংসতা (মারামারি বা সমর্থকদের ওপর হামলা)
            </option>
            <option value="ভীতি প্রদর্শন ও হুমকি">ভীতি প্রদর্শন ও হুমকি</option>
            <option value="ভোটকেন্দ্র দখল ও বিশৃঙ্খলা">ভোটকেন্দ্র দখল ও বিশৃঙ্খলা</option>
            <option value="প্রচারকালীন সহিংসতা">প্রচারকালীন সহিংসতা</option>
            <option value="ভোট-পরবর্তী সহিংসতা">ভোট-পরবর্তী সহিংসতা</option>
            <option value="গুজব ও ভুল তথ্য">গুজব ও ভুল তথ্য প্রচার</option>
            <option value="প্রশাসন বা আইনশৃঙ্খলা বাহিনীর সঙ্গে সংঘর্ষ">
              প্রশাসন বা আইনশৃঙ্খলা বাহিনীর সঙ্গে সংঘর্ষ
            </option>
            <option value="রাজনৈতিক প্রতিপক্ষের মধ্যে সংঘর্ষ">
              রাজনৈতিক প্রতিপক্ষের মধ্যে সংঘর্ষ
            </option>
          </select>
          {errors.incidentType && <p className={errorClassName}>{errors.incidentType.message}</p>}
        </div>

        <div>
          <label className="block text-xs sm:text-sm font-bold text-gray-700 mb-1.5 sm:mb-2">
            এলাকা / সংসদীয় আসন <span className="text-red-500">*</span>
          </label>
          <select
            className="w-full px-3 py-2 sm:px-4 sm:py-3 rounded-lg sm:rounded-xl border border-gray-200 text-sm focus:border-red-500 focus:ring-2 focus:ring-red-100 outline-none transition bg-white"
            {...register('incidentArea', { required: 'এলাকা নির্বাচন করুন' })}
          >
            <option value="ঢাকা-১০">ঢাকা-১০</option>
            <option value="চট্টগ্রাম-৮">চট্টগ্রাম-৮</option>
            <option value="সিলেট-১">সিলেট-১</option>
            <option value="খুলনা-২">খুলনা-২</option>
            <option value="রাজশাহী-১">রাজশাহী-১</option>
          </select>
          {errors.incidentArea && <p className={errorClassName}>{errors.incidentArea.message}</p>}
        </div>
      </div>

      <div>
        <label className="block text-sm font-bold text-gray-700 mb-2">
          মিডিয়া লিংক (YouTube/Facebook)
        </label>
        <input
          type="url"
          placeholder="https://youtube.com/watch?v=... বা ফেসবুক পোস্ট লিংক"
          className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-red-500 focus:ring-2 focus:ring-red-100 outline-none transition"
          {...register('mediaLink', {
            pattern: {
              value: /^(https?:\/\/|$)/,
              message: 'সঠিক লিংক লিখুন',
            },
          })}
        />
        {errors.mediaLink && <p className={errorClassName}>{errors.mediaLink.message}</p>}
      </div>

      <div>
        <label className="block text-sm font-bold text-gray-700 mb-2">মিডিয়া (ছবি/ভিডিও)</label>
        <div className="border-2 border-dashed border-gray-300 rounded-xl p-8 text-center hover:bg-gray-50 transition cursor-pointer relative">
          <input
            type="file"
            accept="image/*,video/*"
            className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
            multiple
            {...register('mediaFiles')}
            onChange={(event) => handleMediaChange(event.target.files)}
          />
          <span className="material-symbols-outlined text-4xl text-gray-400 mb-2">
            cloud_upload
          </span>
          <p className="text-sm text-gray-500">ফাইল নির্বাচন করুন বা ড্রাগ করুন</p>
          {mediaPreviews.length > 0 && (
            <div className="flex gap-2 mt-4 justify-center flex-wrap">
              {mediaPreviews.map((preview, index) => (
                <img
                  key={index}
                  src={preview}
                  alt="Preview"
                  className="w-16 h-16 object-cover rounded-lg border border-gray-200"
                />
              ))}
            </div>
          )}
        </div>
      </div>

      <div>
        <label className="block text-sm font-bold text-gray-700 mb-2">
          বিস্তারিত বিবরণ <span className="text-red-500">*</span>
        </label>
        <textarea
          rows={5}
          placeholder="কি ঘটেছে বিস্তারিত লিখুন..."
          className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-red-500 focus:ring-2 focus:ring-red-100 outline-none transition"
          {...register('description', {
            required: 'বিস্তারিত বিবরণ আবশ্যক',
            minLength: { value: 20, message: 'কমপক্ষে ২০ অক্ষর লিখুন' },
          })}
        />
        {errors.description && <p className={errorClassName}>{errors.description.message}</p>}
      </div>

      <div className="flex justify-end pt-2">
        <button
          type="submit"
          disabled={isSubmitting}
          className="w-full md:w-auto md:px-16 bg-red-600 text-white py-4 rounded-xl font-bold hover:bg-red-700 transition shadow-lg flex items-center justify-center gap-2 disabled:opacity-60"
        >
          <span>{isSubmitting ? 'জমা হচ্ছে...' : 'জমা দিন'}</span>
          <span
            className={`material-symbols-outlined text-lg ${isSubmitting ? 'animate-spin' : ''}`}
          >
            {isSubmitting ? 'refresh' : 'send'}
          </span>
        </button>
      </div>
    </form>
  );
}
