import React, { useEffect, useState } from 'react';
import { Modal } from '@/components/common/modal';
import { useForm } from 'react-hook-form';
import { ChevronDown } from 'lucide-react';
import { Task } from '@/types';

interface DailyReportModalProps {
  isOpen: boolean;
  onClose: () => void;
  task: Task | null;
  elapsedHours: number;
  onSubmit: (data: DailyReportFormData) => void;
}

export interface DailyReportFormData {
  projectId: string;
  taskId: string;
  status: "TODO" | "IN_PROGRESS" | "REVIEW" | "TESTING" | "COMPLETED" | "BLOCKED" | "HOLD" | "PENDING";
  hours: number;
  minutes: number;
  hoursWorked?: number;
  progressPercentage: number;
  workDoneToday: string;
  tomorrowPlan: string;
  hasBlockers: boolean;
  blockers: string;
  taskComments: string;
}

export const DailyReportModal: React.FC<DailyReportModalProps> = ({
  isOpen,
  onClose,
  task,
  elapsedHours,
  onSubmit,
}) => {
  const { register, handleSubmit, reset, watch, setValue, formState: { errors } } = useForm<DailyReportFormData>({
    defaultValues: {
      projectId: '',
      taskId: '',
      status: 'TODO',
      hours: 0,
      minutes: 0,
      progressPercentage: 0,
      workDoneToday: '',
      tomorrowPlan: '',
      hasBlockers: false,
      blockers: '',
      taskComments: ''
    }
  });

  const hasBlockers = watch('hasBlockers');
  const progressPercentage = watch('progressPercentage');
  const status = watch('status');

  useEffect(() => {
    if (status === 'COMPLETED') {
      setValue('progressPercentage', 100);
    }
  }, [status, setValue]);

  useEffect(() => {
    if (task && isOpen) {
      const h = Math.floor(elapsedHours);
      const m = Math.round((elapsedHours - h) * 60);

      reset({
        projectId: task.projectId || (task as any).project?.id || '',
        taskId: task.id || '',
        status: task.status || 'TODO',
        hours: h > 0 ? h : 0,
        minutes: m > 0 ? m : 0,
        progressPercentage: Number((task as any).progressPercentage) || 0,
        workDoneToday: '',
        tomorrowPlan: '',
        hasBlockers: false,
        blockers: '',
        taskComments: ''
      });
    }
  }, [task, isOpen, elapsedHours, reset]);

  const handleFormSubmit = (data: DailyReportFormData) => {
    data.hoursWorked = Number(data.hours) + (Number(data.minutes) / 60);
    onSubmit(data);
  };

  return (
    <Modal isOpen={isOpen} onClose={onClose} className="max-w-[700px] m-4">
      <div className="no-scrollbar relative w-full max-w-[700px] rounded-3xl bg-white p-4 lg:p-8">
        <div className="px-2 pr-14 mb-6">
          <h4 className="text-xl lg:text-2xl font-semibold text-brand-950">
            Submit Daily Work Report
          </h4>
          <p className="text-sm text-gray-500 mt-1">
            Task: <span className="font-medium text-gray-700">{task?.title}</span>
          </p>
        </div>

        <form onSubmit={handleSubmit(handleFormSubmit)} className="px-2 space-y-5">
          <input type="hidden" {...register("taskId")} />
          <input type="hidden" {...register("projectId")} />
          <div className="grid grid-cols-1 gap-x-6 gap-y-5 lg:grid-cols-2">

            <div className="col-span-2 lg:col-span-1">
              <label className="mb-1.5 block text-sm font-medium text-gray-700">Status</label>
              <div className="relative">
                <select
                  {...register("status")}
                  className="h-11 w-full rounded-lg border border-gray-300 appearance-none pl-4 pr-8 py-2.5 text-sm shadow-theme-xs bg-transparent text-gray-800 outline-none"
                >
                  <option value="TODO">TODO</option>
                  <option value="IN_PROGRESS">IN_PROGRESS</option>
                  <option value="REVIEW">REVIEW</option>
                  <option value="TESTING">TESTING</option>
                  <option value="COMPLETED">COMPLETED</option>
                  <option value="BLOCKED">BLOCKED</option>
                  <option value="HOLD">HOLD</option>
                  <option value="PENDING">PENDING</option>
                </select>
                <span className="absolute text-gray-500 -translate-y-1/2 pointer-events-none right-3 top-1/2">
                  <ChevronDown size={20} />
                </span>
              </div>
            </div>

            <div className="col-span-2 lg:col-span-1">
              <label className="mb-1.5 block text-sm font-medium text-gray-700">Time Logged</label>
              <div className="flex items-center gap-3">
                <div className="flex items-center gap-2 flex-1 relative">
                  <input
                    type="number"
                    min="0"
                    readOnly
                    {...register("hours", { valueAsNumber: true })}
                    className="h-11 w-full rounded-lg border border-gray-300 appearance-none pl-4 pr-8 py-2.5 text-sm shadow-theme-xs bg-gray-50 cursor-not-allowed text-gray-500 outline-none"
                  />
                  <span className="absolute right-3 text-sm text-gray-400 pointer-events-none">hr</span>
                </div>
                <div className="flex items-center gap-2 flex-1 relative">
                  <input
                    type="number"
                    min="0"
                    max="59"
                    readOnly
                    {...register("minutes", { valueAsNumber: true })}
                    className="h-11 w-full rounded-lg border border-gray-300 appearance-none pl-4 pr-9 py-2.5 text-sm shadow-theme-xs bg-gray-50 cursor-not-allowed text-gray-500 outline-none"
                  />
                  <span className="absolute right-3 text-sm text-gray-400 pointer-events-none">min</span>
                </div>
              </div>
            </div>

            <div className="col-span-2">
              <label className="mb-1.5 flex items-center justify-between text-sm font-medium text-gray-700">
                <span>Progress Percentage</span>
                <span className="text-brand-950">{progressPercentage}%</span>
              </label>
              <div className="h-11 flex items-center">
                <input
                  type="range"
                  min="0"
                  max="100"
                  step="1"
                  {...register("progressPercentage", { valueAsNumber: true })}
                  className="w-full accent-brand-950"
                />
              </div>
            </div>

            <div className="col-span-2">
              <label className="mb-1.5 block text-sm font-medium text-gray-700">Work Done Today</label>
              <textarea
                {...register("workDoneToday", { required: "Work completed is required" })}
                className="w-full rounded-lg border border-gray-300 appearance-none px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 outline-none min-h-[100px]"
                placeholder="What did you work on today?"
              />
              {errors.workDoneToday && <p className="text-red-500 text-xs mt-1">{errors.workDoneToday.message}</p>}
            </div>

            <div className="col-span-2">
              <label className="mb-1.5 block text-sm font-medium text-gray-700">Tomorrow's Plan</label>
              <textarea
                {...register("tomorrowPlan")}
                className="w-full rounded-lg border border-gray-300 appearance-none px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 outline-none min-h-[80px]"
                placeholder="What is your plan for tomorrow?"
              />
            </div>

            <div className="col-span-2 ">
              <label className="mb-1.5 block text-sm font-medium text-gray-700">Any Blockers?</label>
              <div className="relative">
                <select
                  {...register("hasBlockers", {
                    setValueAs: (v) => v === "true" || v === true
                  })}
                  className="h-11 w-full rounded-lg border border-gray-300 appearance-none px-4 py-2.5 text-sm shadow-theme-xs bg-transparent text-gray-800 outline-none"
                >
                  <option value="false">No</option>
                  <option value="true">Yes</option>
                </select>
                <span className="absolute text-gray-500 -translate-y-1/2 pointer-events-none right-3 top-1/2">
                  <ChevronDown size={20} />
                </span>
              </div>
            </div>

            {hasBlockers && (
              <div className="col-span-2">
                <label className="mb-1.5 block text-sm font-medium text-gray-700">Describe Blockers</label>
                <textarea
                  {...register("blockers", { required: "Please describe the blockers" })}
                  className="w-full rounded-lg border border-gray-300 appearance-none px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 outline-none min-h-[80px]"
                  placeholder="What is blocking your progress?"
                />
                {errors.blockers && <p className="text-red-500 text-xs mt-1">{errors.blockers.message}</p>}
              </div>
            )}

            <div className="col-span-2">
              <label className="mb-1.5 block text-sm font-medium text-gray-700">Task Comments (Optional)</label>
              <textarea
                {...register("taskComments")}
                className="w-full rounded-lg border border-gray-300 appearance-none px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 outline-none min-h-[80px]"
                placeholder="Add any comments to the task..."
              />
            </div>
          </div>

          <div className="flex items-center gap-3 mt-6 lg:justify-end">
            <button
              type="button"
              onClick={onClose}
              className="flex items-center justify-center gap-2 rounded-lg border border-gray-300 bg-[#f7f8fa] px-4 py-3 text-sm font-medium text-gray-700"
            >
              Cancel
            </button>
            <button
              type="submit"
              className="inline-flex items-center justify-center font-medium gap-2 rounded-lg transition px-4 py-3 text-sm bg-brand-950 text-white shadow-theme-xs hover:text-brand-950 hover:bg-yellow-500"
            >
              Submit Report
            </button>
          </div>
        </form>
      </div>
    </Modal>
  );
};
