import { useEffect, useState } from 'react';
import { authService } from '@/lib/auth-service';
import {
  getSubmitReadinessIssues,
  normalizeEmployeeIdInput,
  ProfileVerificationBadge,
  StaffProfileFormFields,
  type StaffFieldState,
  type StaffProfileDto,
} from '@/components/profile';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Loader2 } from 'lucide-react';
import { toast } from 'sonner';

type Props = {
  isDemoMode: boolean;
  initialStaff?: StaffProfileDto;
  onStaffUpdated: (staff: StaffProfileDto) => void;
};

function staffToFields(s: StaffProfileDto): StaffFieldState {
  return {
    employeeId: s.employeeId,
    academicTitleCode: s.academicTitleCode,
    academicTitleOther: s.academicTitleOther,
    unitId: s.unitId,
    unitNameFreetext: s.unitNameFreetext,
    jobTitle: s.jobTitle,
  };
}

export function ApplicantStaffProfileSection({ isDemoMode, initialStaff, onStaffUpdated }: Props) {
  const [staff, setStaff] = useState<StaffFieldState>(() =>
    initialStaff ? staffToFields(initialStaff) : {
      employeeId: null,
      academicTitleCode: null,
      academicTitleOther: null,
      unitId: null,
      unitNameFreetext: null,
      jobTitle: null,
    },
  );
  const [meta, setMeta] = useState<Pick<StaffProfileDto, 'profileVerificationStatus' | 'version' | 'rejectionReason'>>(() => ({
    profileVerificationStatus: initialStaff?.profileVerificationStatus ?? 'draft',
    version: initialStaff?.version ?? 1,
    rejectionReason: initialStaff?.rejectionReason ?? null,
  }));

  const [saving, setSaving] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    if (initialStaff) {
      setStaff(staffToFields(initialStaff));
      setMeta({
        profileVerificationStatus: initialStaff.profileVerificationStatus,
        version: initialStaff.version,
        rejectionReason: initialStaff.rejectionReason,
      });
    }
  }, [initialStaff]);

  const frozen = meta.profileVerificationStatus === 'pending';
  const canSubmit = meta.profileVerificationStatus === 'draft' || meta.profileVerificationStatus === 'rejected';

  const handleSaveStaff = async () => {
    setError('');
    if (isDemoMode) {
      toast.info('Chế độ demo — không lưu hồ sơ nhân sự.');
      return;
    }
    if (frozen) {
      setError('Hồ sơ đang chờ xác minh — không thể chỉnh sửa.');
      return;
    }
    setSaving(true);
    const emp = normalizeEmployeeIdInput(staff.employeeId ?? undefined);
    const res = await authService.updateProfile({
      employeeId: emp,
      academicTitleCode: staff.academicTitleCode,
      academicTitleOther: staff.academicTitleOther,
      unitId: staff.unitId,
      unitNameFreetext: staff.unitNameFreetext,
      jobTitle: staff.jobTitle,
    });
    if (res.success) {
      const sp = res.profile.staffProfile;
      if (sp) {
        onStaffUpdated(sp);
        setMeta({
          profileVerificationStatus: sp.profileVerificationStatus,
          version: sp.version,
          rejectionReason: sp.rejectionReason,
        });
      }
      toast.success('Đã cập nhật hồ sơ nhân sự.');
    } else {
      setError(res.error);
    }
    setSaving(false);
  };

  const handleSubmitVerification = async () => {
    setError('');
    if (isDemoMode) {
      toast.info('Chế độ demo — không gửi xác minh.');
      return;
    }
    const fullStaff: StaffProfileDto = {
      ...staff,
      ...meta,
      verificationSubmittedAt: null,
      verifiedAt: null,
      verifiedByUserId: null,
    };
    const issues = getSubmitReadinessIssues(fullStaff);
    if (issues.length) {
      setError(issues.join(' '));
      return;
    }
    setSubmitting(true);
    const emp = normalizeEmployeeIdInput(staff.employeeId ?? undefined);
    const saveRes = await authService.updateProfile({
      employeeId: emp,
      academicTitleCode: staff.academicTitleCode,
      academicTitleOther: staff.academicTitleOther,
      unitId: staff.unitId,
      unitNameFreetext: staff.unitNameFreetext,
      jobTitle: staff.jobTitle,
    });
    if (!saveRes.success) {
      setError(saveRes.error);
      setSubmitting(false);
      return;
    }
    const res = await authService.submitProfileVerification();
    if (res.success) {
      const sp = res.profile.staffProfile;
      if (sp) {
        onStaffUpdated(sp);
        setMeta({
          profileVerificationStatus: sp.profileVerificationStatus,
          version: sp.version,
          rejectionReason: sp.rejectionReason,
        });
      }
      toast.success('Đã gửi hồ sơ chờ quản trị xác minh.');
    } else {
      setError(res.error);
    }
    setSubmitting(false);
  };

  return (
    <Card>
      <CardHeader>
        <div className="flex flex-wrap items-center justify-between gap-2">
          <div>
            <CardTitle>Hồ sơ nhân sự</CardTitle>
            <CardDescription>Mã nhân sự, học hàm/vị, đơn vị và chức vụ — xác minh bởi quản trị.</CardDescription>
          </div>
          <ProfileVerificationBadge status={meta.profileVerificationStatus} />
        </div>
      </CardHeader>
      <CardContent className="space-y-4">
        {meta.rejectionReason && meta.profileVerificationStatus === 'rejected' ? (
          <Alert variant="destructive">
            <AlertDescription>Lý do từ chối: {meta.rejectionReason}</AlertDescription>
          </Alert>
        ) : null}
        {error ? (
          <Alert variant="destructive">
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        ) : null}
        <StaffProfileFormFields
          value={staff}
          onChange={setStaff}
          disabled={isDemoMode || frozen}
          idPrefix="applicant-staff"
        />
        <div className="flex flex-wrap gap-2">
          <Button type="button" onClick={() => void handleSaveStaff()} disabled={saving || isDemoMode || frozen}>
            {saving ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
            Lưu hồ sơ nhân sự
          </Button>
          {canSubmit ? (
            <Button
              type="button"
              variant="secondary"
              onClick={() => void handleSubmitVerification()}
              disabled={submitting || isDemoMode}
            >
              {submitting ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
              Gửi xác minh
            </Button>
          ) : null}
        </div>
      </CardContent>
    </Card>
  );
}
