'use client';

import React, { useState } from 'react';
import { X, Upload, FileText, CheckCircle2, Download, HelpCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useSubmitInstituteAgreement } from '@/services/instituteKyc/queries';
import { InstituteKycRequestItem } from '@/services/instituteKyc/api';
import { useSettingByKey } from '@/services/settings/queries';
import { getAssetUrl } from '@/lib/getAssetUrl';

interface ModalProps {
  request: InstituteKycRequestItem;
  onClose: () => void;
}

export default function SubmitInstituteAgreementModal({ request, onClose }: ModalProps) {
  const [file, setFile] = useState<File | null>(null);
  const [remarks, setRemarks] = useState('');
  const [acceptedTerms, setAcceptedTerms] = useState(false);

  // Fetch official uploaded agreement & FAQ templates from settings engine
  const { data: agreementSetting } = useSettingByKey('INSTITUTE_AGREEMENT_PDF');
  const { data: faqSetting } = useSettingByKey('INSTITUTE_AGREEMENT_FAQ_PDF');

  const submitMutation = useSubmitInstituteAgreement();

  const agreementFileUrl = getAssetUrl((agreementSetting?.value as any)?.fileUrl);
  const faqFileUrl = getAssetUrl((faqSetting?.value as any)?.fileUrl);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!file) return;

    submitMutation.mutate(
      { requestId: request.id, file, remarks },
      { onSuccess: () => onClose() }
    );
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4 animate-in fade-in duration-200">
      <div className="bg-background border border-border/80 rounded-xl max-w-lg w-full p-6 space-y-4 shadow-xl select-none">
        
        {/* HEADER */}
        <div className="flex items-center justify-between border-b border-border/40 pb-3">
          <div className="flex items-center gap-2">
            <FileText className="h-4 w-4 text-primary" />
            <h2 className="text-xs font-bold uppercase tracking-wider text-foreground">
              Institute Agreement Execution • {request.institute?.name || 'Institute Node'}
            </h2>
          </div>
          <button onClick={onClose} className="text-muted-foreground hover:text-foreground">
            <X className="h-4 w-4" />
          </button>
        </div>

        {/* OFFICIAL DOWNLOAD SECTION */}
        <div className="p-3 bg-muted/20 border border-border/40 rounded-lg space-y-2">
          <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground/80 block">
            Step 1: Download & Review Official Templates
          </span>
          <div className="flex flex-wrap items-center gap-2">
            {agreementFileUrl ? (
              <a
                href={agreementFileUrl}
                target="_blank"
                rel="noreferrer"
                download
                className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-primary/10 border border-primary/30 text-primary hover:bg-primary/20 rounded-md text-xs font-semibold transition-colors"
              >
                <Download className="h-3.5 w-3.5" />
                <span>Download Institute Agreement PDF</span>
              </a>
            ) : (
              <span className="text-[11px] text-muted-foreground italic">Agreement PDF Template Pending</span>
            )}

            {faqFileUrl && (
              <a
                href={faqFileUrl}
                target="_blank"
                rel="noreferrer"
                download
                className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-muted border border-border/60 text-foreground hover:bg-muted/80 rounded-md text-xs font-semibold transition-colors"
              >
                <HelpCircle className="h-3.5 w-3.5 text-primary" />
                <span>Agreement FAQ</span>
              </a>
            )}
          </div>
        </div>

        {/* AGREEMENT TERMS VIEW */}
        <div className="bg-muted/30 border border-border/40 p-3 rounded-lg text-xs space-y-2 max-h-32 overflow-y-auto">
          <p className="font-bold text-foreground">Terms & Operational Governance:</p>
          <p className="text-muted-foreground/80 leading-relaxed text-[11px]">
            {request.agreementText ||
              'By uploading this signed agreement, you agree to govern operations for this assigned institute according to operational compliance guidelines.'}
          </p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          {/* FILE UPLOAD FIELD */}
          <div className="space-y-1.5">
            <label className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">
              Step 2: Upload Signed Agreement Document (PDF/Image max 10MB)
            </label>
            <div className="border border-dashed border-border/80 rounded-lg p-4 text-center hover:border-primary transition-colors cursor-pointer relative bg-muted/10">
              <input
                type="file"
                accept=".pdf,.png,.jpg,.jpeg"
                onChange={(e) => setFile(e.target.files?.[0] || null)}
                className="absolute inset-0 opacity-0 cursor-pointer"
                required
              />
              <Upload className="h-5 w-5 mx-auto text-muted-foreground mb-1" />
              <span className="text-xs font-medium text-foreground block">
                {file ? file.name : 'Click to select or drag signed document'}
              </span>
            </div>
          </div>

          {/* REMARKS FIELD */}
          <div className="space-y-1.5">
            <label className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">
              Remarks / Submitter Notes
            </label>
            <textarea
              value={remarks}
              onChange={(e) => setRemarks(e.target.value)}
              placeholder="Add optional notes for the approver..."
              className="w-full text-xs p-2.5 bg-muted/20 border border-border/40 rounded-lg focus:outline-none focus:border-primary"
              rows={2}
            />
          </div>

          {/* TERMS CHECKBOX */}
          <label className="flex items-center gap-2 cursor-pointer">
            <input
              type="checkbox"
              checked={acceptedTerms}
              onChange={(e) => setAcceptedTerms(e.target.checked)}
              className="rounded border-border"
              required
            />
            <span className="text-[11px] text-muted-foreground/90 font-medium">
              I verify that the uploaded document contains my official physical signature.
            </span>
          </label>

          {/* ACTIONS */}
          <div className="flex justify-end gap-2 pt-2 border-t border-border/40">
            <Button type="button" variant="outline" onClick={onClose} className="h-8 text-xs font-bold">
              Cancel
            </Button>
            <Button
              type="submit"
              disabled={!file || !acceptedTerms || submitMutation.isPending}
              className="h-8 text-xs font-bold gap-1.5 bg-primary text-primary-foreground"
            >
              <CheckCircle2 className="h-3.5 w-3.5" />
              <span>{submitMutation.isPending ? 'Submitting...' : 'Submit Signed Agreement'}</span>
            </Button>
          </div>
        </form>
      </div>
    </div>
  );
}